15. 三数之和

class Solution {
    public List> threeSum(int[] nums) {
        List> iListList = new ArrayList>();
        Arrays.sort(nums);

        for (int first = 0; first < nums.length; first++) {
            int second = first + 1;
            int third = nums.length - 1;

            while (second < third) {
                int temp = nums[second] + nums[third];

                if (temp > (-nums[first])) {
                    third--;
                } else if (temp < (-nums[first])) {
                    second++;
                } else {
                    List iList = new ArrayList();
                    iList.add(nums[first]);
                    iList.add(nums[second]);
                    iList.add(nums[third]);
                    iListList.add(iList);

                    while (second < third && nums[second] == nums[second + 1]) {
                        second++;
                    }

                    second++;

                    while (second < third && nums[third] == nums[third - 1]) {
                        third--;
                    }

                    third--;
                }
            }

            while (first < nums.length - 1 && nums[first] == nums[first + 1]) {
                first++;
            }
        }

        return iListList;
    }
}
15. 三数之和_第1张图片
image.png

你可能感兴趣的:(15. 三数之和)