
思路:排序+双指针

问题就变成:在一个排序数组中找到所有的两数之和使得其和等于一个特殊值?可以通过双指针法在O(N)时间内解决这个问题。即两个指针分别指向数组的首尾,如果和小于目标值,头指针向后移,使得和增大;如果和大于目标值,尾指针向前移,使得和减小。
——时间复杂度:O(N^2),其中 N 是数组nums 的长度。
——空间复杂度:O(logN)。我们忽略存储答案的空间,额外的排序的空间复杂度为 O(logN)。然而我们修改了输入的数组 nums,在实际情况下不一定允许,因此也可以看成使用了一个额外的数组存储了 nums 的副本并进行排序,空间复杂度为 O(N)。
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int n = nums.length;
Arrays.sort(nums);
List<List<Integer>> ans = new ArrayList<List<Integer>>();
// 枚举 a
for (int first = 0; first < n; ++first) {
// 需要和上一次枚举的数不相同
if (first > 0 && nums[first] == nums[first - 1]) {
continue;
}
// c 对应的指针初始指向数组的最右端
int third = n - 1;
int target = -nums[first];
// 枚举 b
for (int second = first + 1; second < n; ++second) {
// 需要和上一次枚举的数不相同
if (second > first + 1 && nums[second] == nums[second - 1]) {
continue;
}
// 需要保证 b 的指针在 c 的指针的左侧
while (second < third && nums[second] + nums[third] > target) {
--third;
}
// 如果指针重合,随着 b 后续的增加
// 就不会有满足 a+b+c=0 并且 b<c 的 c 了,可以退出循环
if (second == third) {
break;
}
if (nums[second] + nums[third] == target) {
List<Integer> list = new ArrayList<Integer>();
list.add(nums[first]);
list.add(nums[second]);
list.add(nums[third]);
ans.add(list);
}
}
}
return ans;
}
}
本文介绍了一种解决三数之和问题的有效算法。通过先排序再利用双指针技术,可以在O(N^2)的时间复杂度内找到数组中所有三个数相加等于特定值的组合。文章详细解释了算法步骤,并提供了具体实现代码。
324

被折叠的 条评论
为什么被折叠?



