当前位置:网站首页>Sum of three numbers: (sort + double pointer + pruning)

Sum of three numbers: (sort + double pointer + pruning)

2022-07-23 10:15:00 Jingle!

public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        //1.  Sort the array first : Sorting algorithm can be used here : Quick sort 、 Merge sort .
        Arrays.sort(nums);
        //2.  Double pointer , One from the front , One from the back 
        for (int i = 0; i < nums.length; i++) {
            // After sorting, if the first element is greater than zero , So no combination can make up a triple , Just return the result directly 
            if (nums[i] > 0) {
                return res;
            }
            // Pruning operation : The first element is de duplicated ;(i > 0 To prevent index exceptions )
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == 0) {
                    res.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    // Skip all duplicate values 
                    while (left < right && nums[right] == nums[right - 1]) {
                        right--;
                    }
                    while (left < right && nums[left] == nums[left + 1]) {
                        left++;
                    }
                    // Find out , Correction and contraction at the same time 
                    right--;
                    left++;
                } else if (sum > 0) {
                    right--;
                } else {
                    left++;
                }
            }
        }
        return res;
    }

原网站

版权声明
本文为[Jingle!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207230319422877.html