[英]3-Sum problem in O(n^2) time and O(1) space
设 A、B 和 C 是三个数组,每个数组包含 n 个整数。 我想找到 3 个整数 a,b,c st a 属于 A,b 属于 B,c 属于 C 和 c=a+b。
方法:
这种方法需要 O(n^2) 空间和 O(n^2) 时间复杂度。 是否可以优化以在 O(n^2) 时间内在没有额外空间的情况下找到 a,b,c(即空间复杂度 = O(1))?
我有以下方法。 这是正确的吗 ?
算法:
1. Sort A and B. Time complexity= O(nlgn) using HeapSort
2. Loop through elements of C
2.1 Take 2 pointers one at beginning of A,
second at end of B. Let this be left and right pointers
and make left parse A and right parse B.
2.2 if A[left] + B[right] == C[index]
then break
else if A[left] + B[right] < C[index]
left++;
else
right--;
第 2 步的时间复杂度 = O(n^2)
总时间复杂度 = O(n^2)
空间复杂度 = O(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.