【发布时间】:2021-11-24 14:51:26
【问题描述】:
假设输入的 n 个整数数组只包含 -5000n 到 6000n 之间的整数。 我们需要找到一种算法来确定数组是否包含三个元素 总和为零,在 O(n log n) 时间内。
我的方法:
1. Sort in O(n log n) time.
2. Run a loop in O(n) time
3. Fix two left and right pointers in the sorted array as the two endpoints
4. find = SUM - (A[left] + A[right])
5. Search for the third element (find) using binary search in O(log n)
6. if found then return TRUE
7. else
8.
我被困在第8步,如果二分搜索算法返回false,那么应该如何调整左右指针?
此外,由于我没有评估所有可能的组合,因此整个算法是否可以在每种情况下找到总和为零的三个元素?
【问题讨论】:
-
-5000n 和 6000n 这些数字中的 n 是什么意思?
-
你能分享一下这个问题的约束吗?
-
[-5000n, 6000n ] 是数组可以包含的整数范围。
-
如果你想要 O(n^2) 求解,我会和你分享
-
如果可能的话,如果可以投票,否则下次我将无法发布。
标签: arrays algorithm time-complexity