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

解法一:暴力,三重循环n3,后来看评论说是能过,我们绕过这种解法。

解法二:排序+双指针

实际上做的时候遇到好多bug,顾头顾不着尾。

思路是这样的,先排序,用三个指针表示这三个数,首先遍历第一个指针i

然后L 指向i左边的第一数,即 i+1

R指向数组最后一个数,即len-1

当L<R时候循环

用sum表示是三个指针指向的数的和

如果sum==0,说明是一组解

如果sum<0,那么只能移动R指针

如果sum>0,那么只能移动L指针。

关键在于去重。

时间复杂度为nlogn+n*2n,即n2

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int> > a;
           sort(nums.begin(),nums.end());
        int len = nums.size();
        for(int i = 0;i < len - 2; ++i){
            if(i!=0 && nums[i] == nums[i-1]){
                continue;
            }
            int L = i + 1;
            int R = len - 1;
            while(L<R){
                if(nums[i] + nums[L] +nums[R] == 0){
                    vector<int> v;
                    v.push_back(nums[i]);
                    v.push_back(nums[L]);
                    v.push_back(nums[R]);
                    a.push_back(v);
                    L++;
                    R--;
                    while(L<R && nums[L]==nums[L-1] && nums[R]==nums[R+1]){
                        L++;
                        R--;
                    }
                    continue;
                }
                while(nums[i]+nums[L]+nums[R]>0 ){               
                    R--;
                    if(R<=L){
                        break;
                    }
                }
                while(nums[i]+nums[L]+nums[R]<0 ){
                    L++;
                    if(L>=R){
                        break;
                    }
                }
            }
        }
        return a; 
    } 
};
Last modification:December 21st, 2019 at 07:58 pm
如果觉得我的文章对你有用,请随意赞赏