LeetCode 15 三数之和
1.思路
双指针,循环
2.代码
public List<List<Integer>> threeSum(int[] nums) {
int length = nums.length;
Arrays.sort(nums);
List<List<Integer>> ans = new ArrayList<>();
for (int first = 0; first < nums.length; first++) {
int target = -nums[first];
// 如果当前值和上一个值相同,则跳出循环 第一个数不能相同
if (first>0 && first == nums[first-1])
continue;
// 第三个指针,指向数组最后一个
int third = length-1;
for (int second = first+1; second <length ; second++) {
if (second>first+1 && nums[second] == nums[second-1])
continue;
while (second<third && nums[second]+nums[third] >target){
third--;
}
if (second == third)
break;
if (nums[second]+nums[third] == target){
List<Integer> list = new ArrayList();
list.add(first);
list.add(second);
list.add(third);
ans.add(list);
}
}
}
return ans;
}
3.代码细节
确保每一个数不重复,first、second、third不能和上一个重复,
if (first>0 && first == nums[first-1])
continue;
if (second>first+1 && nums[second] == nums[second-1])
continue;
在third–的过程中,确保second<third,否则third–终止
3.
当second = third的时候,下一次循环时second增加,必然没有合适的值达到target,第二层循环终止
4.
在thrid–结束时,会有两种情况,1.second = =third,则二层循环结束,2.num[second]+nums[third] = target,找到合适三个数,放入ans中。