c# - 在数组中,我们如何找到 2 个元素在给定数字中的差异..?少于 O(n^2) 时间

标签 c# java c algorithm data-structures

<分区>

Possible Duplicate:
checking if 2 numbers of array add up to I

我的问题是我有一个给定的数字 no=10; 假设和一个数组 A 我必须找到那些没有谁的区别是给定的 no.. 例如:- A[5]-A[3]=10; 然后打印 print(A[5]);打印(A[5])
我有一个算法可以在 O(n^2) 时间内完成,但我们需要更好的东西...
我的直觉是可能会在将数组短路后做一些事情......但是如何......因为在短路后它还需要两个循环来检查该条件......
我有点困惑......

最佳答案

原始答案 - O(n log n)

怎么样:

  • 对数组(或副本)进行排序。这是 O(n log n)
  • 遍历数组,对每个值 x 进行二分查找 x + no
    • 每次二分查找都是O(log n)
    • 总体 O(n log n)

总成本:O(n log n)


根据 Steve Jessop 的评论对上述内容进行修改:

FWIW, you don't have to do a binary search for x + no. As you iterate over the array, you can maintain a second iteration point in advance of the first one. Since the array is sorted, at each step x + no is greater than or equal to what x + no was in the previous step, so a linear search starting at the second iteration point from the previous step only ever goes forward and hence is O(n) total for the whole outer iteration, even though it isn't O(1) for each of the n steps.

这仍然需要事先进行排序,不过这是 O(n log n)。


IMO 最佳答案(易于实现且复杂度为 O(n))

编辑:或者,当然,构建一个 HashSet 来更快地进行包含检查(假设创建集合的时间复杂度为 O(n),查找时间为 O(1)):

HashSet<int> values = new HashSet<int>(array);
foreach (int value in array)
{
    if (values.Contains(value + no))
    {
        // Found a match
    }
}

关于c# - 在数组中,我们如何找到 2 个元素在给定数字中的差异..?少于 O(n^2) 时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7833947/

相关文章:

c# - 声明父类(super class)时无法访问子类的通用属性

c# - 使用单例设计模式时,首选哪种结构,为什么?

java - 是否可以在不使用paintComponent(Graphics g)的情况下获得正确的字符串大小?

java - 使用断言 Java

c - C中的算法

c - 从内存创建的 SDL 纹理仅以黑白渲染

c# - 为什么我不能将此对象作为参数传递?

c# - 如何从 C# 打开 "My Documents"和 "My Computer"文件夹?

java - Spring AOP 与 AspectJ

c - long double 的用法