Contents

LeetCode15三数之和

Contents

三数之和

public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        int n = nums.length;
        Arrays.sort(nums);
        for (int first = 0; first < n; first++) {
            if(first > 0 && nums[first] == nums[first - 1]){
                continue;
            }
            int third = n - 1;
            for (int second = first + 1; second < n; second++) {
                //重复跳过
                if(second > first + 1 && nums[second] == nums[second - 1]){
                    continue;
                }
                //在遍历第二个的时候,同时从右向左找第三个,避免再次循环
                while (nums[first] + nums[second] + nums[third] > 0 && third > second){
                    third--;
                }
                if(third == second){
                    break;
                }
                if(nums[first] + nums[second] + nums[third] == 0){
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[first]);
                    list.add(nums[second]);
                    list.add(nums[third]);
                    result.add(list);
                }
            }
        }
        return result;
    }

tag:双指针、排序、数组