Skip to main content

🟡 剑指 Offer II 007. 数组中和为 0 的三个数

LeetCode 提示

题目难度 中等

原题链接 🔗 leetcode

题解1#

排序+双指针。参考006题的两数之和实现

class Solution {    private List<List<Integer>> twoSum(int[] numbers, int target, int left) {        List<List<Integer>> res = new ArrayList<>();
        int right = numbers.length-1, sum;        while (left < right) {            sum = numbers[left] + numbers[right] - target;
            if (sum == 0) {                res.add(new ArrayList<>(Arrays.asList(numbers[left], numbers[right])));
                left += 1;                while (left < right && numbers[left] == numbers[left-1]) {                    left += 1;                }
                continue;            }
            if (sum > 0) {                right -= 1;            } else {                left += 1;            }        }
        return res;    }
    public List<List<Integer>> threeSum(int[] nums) {        List<List<Integer>> ans = new ArrayList<>();        Arrays.sort(nums);
        for (int i=0; i<nums.length; i+=1) {            if (i>0 && nums[i] == nums[i-1]) {                continue;            }            List<List<Integer>> res = twoSum(nums, 0-nums[i], i+1);            for (List<Integer> cur : res) {                cur.add(nums[i]);                ans.add(cur);            }        }
        return ans;    }}