【LeetCode算法练习(C++)】3Sum

题目:
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

链接:3Sum

解法:排序,之后拿出第一个数,转化为两数和问题,注意外层循环到倒数第三个数。时间O(n^2)

class Solution {
public:
    vector<vector<int> > threeSum(vector<int>& nums) {
        vector<int> numSet(3);
        vector< vector<int> > ans;
        sort(nums.begin(), nums.end());
        int sum;
        int len = nums.size();
        for(int i = 0; i < len - 2; i++) {
            sum = 0 - nums[i];
            numSet[0] = nums[i];
            for(int j = i + 1, k = len - 1; j < k;) {
                if(nums[j] + nums[k] == sum) {
                    numSet[1] = nums[j++];
                    numSet[2] = nums[k--];
                    ans.push_back(numSet);
                    while(j < k && nums[j] == nums[j-1]) 
                        j++;
                    while(j < k && nums[k] == nums[k+1])
                        k--;
                }
                else if(nums[j] + nums[k] < sum)
                    j++;
                else 
                    k--;
            }
            while(i < len - 2 && nums[i + 1] == nums[i])
                i++;
        }
        return ans;
    }
};

Runtime: 109 ms

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值