题目

在这里插入图片描述
(这里面最重要的就是对重复元素的跳过处理)

代码及详细注释

class Solution {
    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> 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;			// (-1、-1、0、2)遍历到第一个重复元素“-1”时,不会触发这个语句,只有第二次遍历到重复元素“这里是-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<R && nums[L] == nums[L+1]) L++; // 去重
                    while (L<R && nums[R] == nums[R-1]) R--; // 去重
                    L++;
                    R--;
                }
                else if (sum < 0) L++;
                else if (sum > 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<List<Integer>> res ;
    public List<List<Integer>> threeSum(int[] nums) {


        res = new ArrayList<>();
        Arrays.sort(nums);
        if(nums.length < 3 || nums[0]>0){
            return res;
        }
        for(int first = 0; first<nums.length;first++){
            if(nums[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<Integer> 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不越界,加上L<R
                        L++;
                    }
                    while(L<R && nums[R-1] == nums[R]){
                        R--;
                    }

                    // 当前的和已经为0,且数组有序,只有 让小的变大(L++),同时大的变小(R--),才有可能让 和 再次等于0
                    L++;       // 使用了while 循环一定要更新变量,不然就是死循环,运行超时
                    R--;
                }else if(temsum>0){
                    R--;
                }else{
                    L++;
                }


            }
        }

    return res;



    }
}

更多推荐