题目代码及详细注释我的代码及注释
题目
(这里面最重要的就是对重复元素的跳过处理)
class Solution {
public static List> threeSum(int[] nums) {
List> ans = new ArrayList();
int len = nums.length;
if(nums == null || len < 3) return ans;
Arrays.sort(nums); // 排序
for (int i = 0; i < len ; i++) {
if(nums[i] > 0) break; // 如果当前数字大于0,则三数之和一定大于0,所以结束循环
if(i > 0 && nums[i] == nums[i-1]) continue; // 去重
int L = i+1;
int R = len-1;
while(L < R){
int sum = nums[i] + nums[L] + nums[R];
if(sum == 0){
ans.add(Arrays.asList(nums[i],nums[L],nums[R]));
while (L 0) R--;
}
}
return ans;
}
}
作者:guanpengchn
链接:https://leetcode-cn.com/problems/3sum/solution/hua-jie-suan-fa-15-san-shu-zhi-he-by-guanpengchn/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
我的代码及注释
class Solution {
List> res ;
public List> threeSum(int[] nums) {
res = new ArrayList<>();
Arrays.sort(nums);
if(nums.length < 3 || nums[0]>0){
return res;
}
for(int first = 0; first 0){
break; // 剪枝,这一轮循环的first大于零,则以后肯定无解了
}
if(first>0 && nums[first] == nums[first-1]){ // 去除first重复的情况,并且涉及到数组下标的时候一定要确保不越界
continue;
}
int L = first + 1;
int R = nums.length -1;
while(L < R){
int temsum = nums[first] + nums[L] + nums[R];
if(temsum == 0){
List path = new ArrayList<>();
path.add(nums[first]);
path.add(nums[L]);
path.add(nums[R]);
res.add(path);
// 跳过重复的数
while(L < R && nums[L] == nums[L+1]){ // 因为while循环可能会一直将L增大,所以要确保L不越界,加上L0){
R--;
}else{
L++;
}
}
}
return res;
}
}



