3 Sum
特别注意,在最外层做for循环的时候,i = 0 ~ size - 2是可以的,但是i = 2 ~ size是不行的,
因为你跳过重复i的时候不能保证前面的所有nums[i]都不会在被用到,所以会丢解。 public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ret = new ArrayList<>();
Arrays.sort(nums);
for(int j = 0; j < nums.length - 2; j++){
if(j == 0 || j > 0 && nums[j] != nums[j-1]){//i去duplicate
int first = nums[j], start = j + 1, end = nums.length - 1;
while(start < end){
if(nums[start] + nums[end] < -first){
start ++;
}else if (nums[start] + nums[end] > -first){
end --;
}else{
List<Integer> triple = new ArrayList<Integer>();
triple.add(first);
int second = nums[start], third = nums[end];
triple.add(second);
triple.add(third);
ret.add(triple);
//剩下俩数去duplicate
while(start < end && second == nums[start])
start ++;
while(start < end && third == nums[end])
end --;
}
}
}
}
return ret;
}Last updated