Description
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.
Note: The solution set must not contain duplicate triplets.
Solution
Three-pointers, O(n^2) time, O(1) space
先对数组进行排序,注意去重。
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> triples = new ArrayList();
if (nums == null || nums.length < 3) {
return triples;
}
Arrays.sort(nums);
int i = 0;
int n = nums.length;
while (i < n - 2) {
int j = i + 1;
int k = n - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum < 0) {
++j;
} else if (sum > 0) {
--k;
} else {
List<Integer> triple = new ArrayList();
triples.add(Arrays.asList(nums[i], nums[j], nums[k])); // elegant!
// exclude duplicate combinations
while (++j < k && nums[j] == nums[j - 1]) {};
while (j < --k && nums[k] == nums[k + 1]) {};
}
}
while(++i < n - 2 && nums[i] == nums[i - 1]) {};
}
return triples;
}
}