阶梯算法与塌缩算法

 public static List<List<Integer>> threeSum(int[] nums) {

        List<List<Integer>> res = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        for(int i = 0 ; i < nums.length ; i++){
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int j = i + 1;
            int target = -nums[i];
            int z = nums.length -1;

            while(j < z){
                if(nums[j] + nums[z] == target){
                    res.add(Arrays.asList(nums[i],nums[j],nums[z]));
                    j++;
                    z--;
                    while(j < z && nums[j] == nums[j - 1]){//去除重复
                        j++;
                    }
                    while(j < z && nums[z] == nums[z + 1]){//去除重复
                        z--;
                    }
                }else if(nums[j] + nums[z] > target){
                    z--;
                }else{
                    j++;
                }
            }
        }
        return res;
    }
点赞