LeetCode 15. 3Sum

给一个vector,输出加起来等于0的组合。

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

C++版本。

class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
	int len=nums.size();
    sort(nums.begin(), nums.end());//96ms 14.6MB

	vector<vector<int>> res;
	for(int i=0;i<len-2;i++){
		int left=-nums[i];
		if(i>0&&nums[i]==nums[i-1]) continue; //相同的数跳过(因为要求不能重复)
        int p=i+1,q=nums.size()-1;            //一个从前往后一个从后往前计数
        while(p<q){
            int tmp = nums[p]+nums[q];
            if(tmp>left){
                q--;
            }else if(tmp<left){
                p++;
            }
            else{                            //a+b+c=0
                res.push_back(vector<int>({nums[i],nums[p],nums[q]}));
                while(p<q&&nums[p]==nums[p+1])p++;
                while(p<q&&nums[q]==nums[q-1])q--;
                p++;
                q--;
            }   
        }
	}
	return res;
}
};

自己写的快排比较慢,还是调用sort就好。

原本我的计数是i=0~len-2;p=i+1~len-1;q=p+1~len,这个复杂度比较高,而且比较不科学,p,q到后面都是比较大的数值。

改成一个从前面开始p,一个从后面q开始比较快。

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值