简体   繁体   English

两个数字x和y来自两个不同的数组。 查找是否存在总和z使得z = x + y

[英]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. 我需要添加的是每个数组中都有n个整数,并且每个整数都在0到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. 您的输入是(例如)32位整数的数组。
  • Adding two integers is an O(1) operation. 两个整数相加是O(1)运算。
  • Your machine has unlimited memory and reading a byte anywhere in memory is an O(1) operation. 您的机器具有无限的内存,并且在内存中的任何位置读取字节都是O(1)操作。

1) Convert one of the arrays into a hash set with approximately O(1) time complexity for lookups. 1)将其中一个数组转换为时间大约为O(1)的哈希集进行查找。 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. 2)遍历另一个数组,并针对每个元素i,检查x-i是否在哈希集中。 If there is a match then (i, x - i) is a solution. 如果有匹配则(i,x - i)是一个解决方案。 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. 我想不出线性时间算法,但我可以想到一个O(m log n)解决方案,其中m是较大列表的长度,n是较小列表的长度。

let n be the length of the smaller list and m be the length of the larger list. 设n是较小列表的长度,m是较大列表的长度。

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. 步骤1:对较小的列表进行排序(例如合并排序):O(n log n)步骤2:对于较大列表中的每个项目,尝试在排序后的列表中查找(目标编号-项目)。 If you find a match, you have found the two numbers you are looking for. 如果找到匹配项,则表示您找到了要查找的两个数字。 O (m log n). 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. 复杂度为O(n log n)+ O(m log n),即O(m log n),因为m是较大的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM