15. 3Sum - Medium

Posted fatttcat

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了15. 3Sum - Medium相关的知识,希望对你有一定的参考价值。

Given an array nums of n integers, are there elements abc 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]
]

 

sort the input array and then run through all indices of a possible first element of a triplet.

for each possible first element, use two pointers like in 2sum problem

skip equal elements to avoid duplicates in the answer without a set

注意:在skip same element的时候,l和r的方法是相反的,应该判断nums[l] = nums[l-1]和nums[r] = nums[r+1]

时间:O(N^2),空间:O(1)

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

 

以上是关于15. 3Sum - Medium的主要内容,如果未能解决你的问题,请参考以下文章

lintcode57 - 3sum - medium

Leetcode涔?5. 3Sum (medium)

leetcode 15. 3Sum

15 & 16. 3Sum & 3Sum Cloest

15. 3Sum

15. 3Sum