[英]Find Two elements in the Array that add up to the Target number in O(n * log n) Time
I have a problem with O(n * log(n)) searching algorithm.我对O(n * log(n))搜索算法有疑问。
I have to find two numbers from an array that add up to the given number.我必须从一个数组中找到两个加起来等于给定数字的数字。
I know how O(n * log(n)) works, but I'm not sure if those two correct numbers will meet in search if I do it like this:我知道O(n * log(n))是如何工作的,但是如果我这样做,我不确定这两个正确的数字是否会在搜索中相遇:
for (int i = 0; i < n; i++)
for (int j = 1; j <= n; j = j*2)
Is there a way to keep O(n * log(n)) complexity so that every two numbers meet in the search?有没有办法保持O(n * log(n))复杂性,以便每两个数字在搜索中相遇?
sort array (O(nlogn))排序数组 (O(nlogn))
for each element:对于每个元素:
2.1 binary search to find other element that adds up to the given number (or to figure out there is none) (O(logn)) 2.1 二进制搜索以找到加起来等于给定数字的其他元素(或找出没有)(O(logn))
Step 2 has complexity O(nlogn), and so the whole algorithm has O(nlogn)步骤 2 的复杂度为 O(nlogn),因此整个算法的复杂度为 O(nlogn)
I have to find two numbers from an array that add up to the given number .
我必须从一个数组中找到两个加起来等于给定数字的数字。
It can be done in O(n) time and utilizing additional O(n) space.它可以在O(n)时间内完成并利用额外的O(n)空间。
For that, we can index all array elements in a Map
.为此,我们可以索引
Map
中的所有数组元素。 The key of the map would be a difference between the target sum and a particular array element and value - an element itself.映射的关键是目标总和与特定数组元素和值之间的差异 - 元素本身。 Creation of the map requires a single iteration over the source array, ie it cost O(n) time.
地图的创建需要对源数组进行一次迭代,即花费O(n)时间。
In the case when the target sum is even and there's only a single array element is exactly equal to the target sum / 2
result would be incorrect.如果目标总和是偶数并且只有一个数组元素完全等于
target sum / 2
,则结果将不正确。 To treat this case, we can count the number of elements that are equal to the half of the sum.为了处理这种情况,我们可以计算等于总和一半的元素的数量。 It can be done simultaneously with the process of generating the map to avoid performing an additional iteration (although it contradicts clean coding practices).
它可以与生成地图的过程同时完成,以避免执行额外的迭代(尽管它与干净的编码实践相矛盾)。
Then we need to examine whether there's an element in the array that that matches one of the keys contained in the map .然后我们需要检查数组中是否存在与map中包含的键之一匹配的元素。 If such an element has been found, then we have a pair of numbers that produces the target sum.
如果找到了这样的元素,那么我们就有一对产生目标总和的数字。
So we need to perform only 2
iterations over the source array, and that result to O(n) overall time complexity.所以我们只需要对源数组执行
2
次迭代,结果就是O(n)的整体时间复杂度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.