15. 3Sum

作者: mikejason8 | 来源:发表于2020-06-20 20:38 被阅读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]
]

思路:

1.先对A排序
2.遍历数组A[0]->A[n-3],对每一位元素A[i], 寻找A[l]+A[r]==0-A[i]的l和r,l=i+1,r=n-1,通过l++和r--两边收缩。
3.注意skip元素重复的情况。

代码

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

相关文章

网友评论

      本文标题:15. 3Sum

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