15. 3Sum
2019-04-20 本文已影响0人
尚无花名
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
这道题要注意的地方是一定要去重。
如果我们先把数字有序化,就能更方便我们去重。
所以这里我们先把nums排序,
然后再把第一个数字pt0从左往右扫:
对每一个pt0, 我们找target 为 0 - nums[pt0]的 2 sum。
对于two sum问题, 我们可以熟练的使用双指针来做。
这里又是要去重:
如果l 指针和它的前一个相等而且l指针不是pt0, 则跳过。
如果r指针和它的后一个相等而且r指针不在最后,则跳过。
然后就是典型的two sum问题了。
代码见下:
public List<List<Integer>> threeSum(int[] nums) {
//sort nums
Arrays.sort(nums);
List<List<Integer>> ans = new ArrayList<>();
//l, r pointer approach
// sweep pt0 from 0 to nums.length - 3;
int pt0 = 0;
while (pt0 < nums.length - 2) {
int target = 0 - nums[pt0];
int l = pt0 + 1, r = nums.length - 1;
if (pt0 > 0 && nums[pt0] == nums[pt0 - 1]) {
pt0++;
continue;
}
while (l < r) {
if (l != pt0 + 1 && nums[l] == nums[l - 1]) {
l++;
continue;
}
if (r != nums.length - 1 && nums[r] == nums[r + 1]) {
r--;
continue;
}
if (nums[l] + nums[r] == target) {
ans.add(Arrays.asList(nums[pt0], nums[l], nums[r]));
l++;
r--;
} else if (nums[l] + nums[r] < target) {
l++;
} else {
r--;
}
}
pt0++;
}
// careful dedup
return ans;
}