15. 3Sum

作者: liuhaohaohao | 来源:发表于2018-06-26 20:07 被阅读0次

    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<List<Integer>> threeSum(int[] nums) {
            Arrays.sort(nums);          //排序
           
            List<List<Integer>> 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

          本文链接:https://www.haomeiwen.com/subject/iwomyftx.html