15. 3Sum

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]
]

Solution

class Solution {
    public List> threeSum(int[] nums) {
        Arrays.sort(nums);          //排序
       
        List> result = new ArrayList<>();
        for (int i = 0; i < nums.length - 2; i++){
            if (i > 0 && nums[i] == nums[i-1])    continue;       //跳过重复答案
            int j = i + 1;
            int k = nums.length - 1;
            int target = -nums[i];
            while (j < k){
                int sum = nums[j] + nums[k];
                if (sum == target){
                    result.add(Arrays.asList(nums[i], nums[j], nums[k]));
                    j++;
                    k--;
                    while (j < k && nums[j] == nums[j-1])   j++;    //跳过重复答案
                    while (j < k && nums[k] == nums[k+1])   k--;    //跳过重复答案
                }else if (sum > target){
                    k--;
                }else if (sum < target){
                    j++;
                }
                
            }
        }
        return result;
    }
}

你可能感兴趣的:(15. 3Sum)