題目
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
給出一個(gè)有n個(gè)整數(shù)的數(shù)組S,在S中找到三個(gè)整數(shù)a, b, c,找到所有使得a + b + c = 0的三元組。
樣例
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
解題思路
這道題,用兩個(gè)指針 Two Pointers的方式做會(huì)比較容易理解,此時(shí)的算法時(shí)間復(fù)雜度是O(n^2)。
要注意的地方有兩個(gè)。
一是要注意提前給數(shù)組排序,用
Arrays.sort();
的方式就可以實(shí)現(xiàn),這個(gè)排序是用快速排序的方式,時(shí)間復(fù)雜度是O(nlogn);
二是要注意由于題目中專門要求了要unique的結(jié)果,所以要排除掉相同的狀況。
具體代碼如下:
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
// skip the same result
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1, right = nums.length - 1;
while (left < right) {
List<Integer> temp = new ArrayList<Integer>();
if (nums[left] + nums[right] + nums[i] == 0) {
temp.add(nums[i]);
temp.add(nums[left]);
temp.add(nums[right]);
res.add(temp);
// skip the same result
while (left < right && nums[left] == nums[left + 1]) {
left++;
}
// skip the same result
while (left < right && nums[right] == nums[right - 1]) {
right--;
}
left++;
right--;
} else if (nums[left] + nums[right] + nums[i] < 0) {
left++;
} else {
right--;
}
}
}
return res;
}