开发者

Two numbers, x and y, are from two different arrays. Find if there is a sum z such that z= x+y

I need to add that 开发者_如何转开发there are n integers in each array, and each integer is between 0 and n^5. Is there any way to solve this problem in linear-time algorithm?


Yes it's possible in linear time under these assumptions:

  • Your inputs are arrays of (for example) 32-bit integers.
  • Adding two integers is an O(1) operation.
  • Your machine has unlimited memory and reading a byte anywhere in memory is an O(1) operation.

1) Convert one of the arrays into a hash set with approximately O(1) time complexity for lookups. Construction of the hash set takes approximately linear time.

2) Iterate over the other array and for each element i, check if x - i is in the hash set. If there is a match then (i, x - i) is a solution. This step requires linear time.


I can not think of a linear time algorithm, but I can think of a O (m log n) solution where m is the length of the larger list and n is the length of the smaller list.

let n be the length of the smaller list and m be the length of the larger list.

Step 1: sort the smaller list (merge sort for example): O(n log n) Step 2: for each item in the larger list, try to find (target number - item) in the sorted list. If you find a match, you have found the two numbers you are looking for. O (m log n).

The complexity is O (n log n) + O (m log n) which is O (m log n) because m is the larger list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜