查找数组中的两个元素的总和为k总和、组中、元素、两个

2023-09-10 22:49:21 作者:奔跑的五花肉

可能重复:   Given两个数组a和b .Find所有元素对(A1,B1),使得A1属于阵列A和B1属于数组b的总和A1 + B1 = K。

考虑:一个排序的数组 A 整数 输入:一个整数 K

Given : An unsorted array A of integers Input : An integer k

输出:所有的这两个元素设置元素的和在每一个设置为 K 在O(N)

Output : All the two element set with sum of elements in each set equal to k in O(n).

例如:

A = {3,4,5,1,4,2}

输入:6 输出: {3,3},{5,1},{4,2}

Input : 6 Output : {3,3}, {5,1}, {4,2}

注:我知道一个O(N LOGN)解决方案,但这需要有数组排序。有没有什么办法由这个问题可以在O(N)来解决。一个不平凡的C ++数据结构可以用,即没有束缚的空间

Note : I know an O(n logn) solution but that would require to have the array sorted. Is there any way by which this problem can be solved in O(n). An non-trivial C++ data structure can be used i.e there's no bound on space

推荐答案

请一个固定时间的查找表(散),所以你可以看到,如果一个特定的整数,包括在你的数组(为O(n))。然后,对于阵列中的每个元素,看看是否 kA的[I] 是包括在内。这需要一定的时间对每个元素,所以一共有O(n)的时间。这是假设元件是不同的;人们不难使其与重复元素工作

Make a constant-time lookup table (hash) so you can see if a particular integer is included in your array (O(n)). Then, for each element in the array, see if k-A[i] is included. This takes constant time for each element, so a total of O(n) time. This assumes the elements are distinct; it is not difficult to make it work with repeating elements.

 
精彩推荐
图片推荐