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.
即在序列中找出和为0的三个数。
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List result = new ArrayList<List<Integer>>();
if (nums == null || nums.length < 3) return result;
for(int i = 0; i < nums.length - 2 && nums[i] <= 0 ; i++) {
if (i > 0 && nums[i] == nums[i-1]) continue;
int left = i + 1;
int right = nums.length - 1;
while (right > left) {
int tmp = nums[i] + nums[left] + nums[right];
if (tmp > 0) while(left < right && nums[--right] == nums[right+1]);
if (tmp < 0) while(left < right && nums[++left] == nums[left-1]);
if (tmp == 0) {
List l = new ArrayList<Integer>();
l.add(nums[i]);
l.add(nums[left]);
l.add(nums[right]);
while(left < right && nums[++left] == nums[left-1]);
while(left < right && nums[--right] == nums[right+1]);
result.add(l);
}
}
}
return result;
}
}