LeetCode 15 3Sum

2018-10-22  本文已影响0人  manayuan

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.

Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        for (int i=0; i<nums.length-2; i++) {
            while (i > 0 && i < nums.length - 2 && nums[i] == nums[i-1]) {
                i ++;
            }
            int l = i + 1, r = nums.length - 1;
            while (l < r) {
                if (nums[l] + nums[r] > - nums[i]) {
                    r --;
                    while (r >= 0 && nums[r+1] == nums[r]) {
                        r --;
                    }
                }
                else if (nums[l] + nums[r] < - nums[i]) {
                    l ++;
                    while (l < nums.length && nums[l-1] == nums[l]) {
                        l ++;
                    }
                }
                else {
                    Integer[] sum = {nums[i], nums[l], nums[r]};
                    res.add(Arrays.asList(sum));
                    r --; l ++;
                    while (r >= 0 && nums[r+1] == nums[r]) {
                        r --;
                    }
                    while (l < nums.length && nums[l-1] == nums[l]) {
                        l ++;
                    }
                }
            }
        }
        return res;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读