leetcode 0015 三数之和 python与C++


一、思路

我们先把数组排序,第一个数一定要小于等于0,否则一定不存在三个数之和为0.
题目要求不重复,首先保证第一个数不重复,当nums【i+1】 等于nums【i】时,就跳过,然后保证后两个数不重复,如果后两个数与第一个数能构成答案,那么和他俩相同的值一定能构成答案,所以把所有相同的值都跳过即可。
接下来说一下思路,首先对数组排序,第一个数要小于等于0,第二个数从第一个数后边一位开始遍历,第三个数从最后一位往前遍历,找到符合答案的,存起来,然后就把第二个第三个数的重复项跳过,继续寻找,知道第二个数与第三个数相遇,则第一个数的所有可能就都遍历完了。
然后遍历完所有第一个数小于等于0的情况即可。

二、代码

代码如下:

1.python

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
    	n = len(nums)
    	if n < 3:
    		return []
    	nums = sorted(nums)
    	res = []
    	for i in range(n):
    		if nums[i] > 0:
    			return res
    		if i > 0 and nums[i] == nums[i-1]:
    			continue
    		l,r = i+1,n-1
    		while l < r:
    			if nums[l] + nums[r] + nums[i] == 0:
    				temp = [nums[i],nums[l],nums[r]]
    				res.append(temp)
    				while l < r and nums[l]==nums[l+1]:
    					l += 1
    				while l < r and nums[r]==nums[r-1]:
    					r -= 1
    				l += 1
    				r -= 1
    			elif nums[l] + nums[r] + nums[i] < 0:
    				l += 1
    			else:
    				r -= 1
    	return res

2.C++

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
    	int n =nums.size();
    	sort(nums.begin(), nums.end());
    	vector<vector<int>> res;
    	if(n<3){
    		return {};
    	}
    	for(int i=0;i<n;i++){
    		if(nums[i]>0){
    			return res;
    		}
    		if(i>0 && nums[i] == nums[i-1]){
    			continue;
    		}
    		int l = i+1;
    		int r = n-1;
    		while(l<r){
    			if(nums[l] + nums[r] + nums[i] == 0){
    				vector<int> temp;
    				temp.push_back(nums[i]);
    				temp.push_back(nums[l]);
    				temp.push_back(nums[r]);
    				res.push_back(temp);
    				while(l<r && nums[l]==nums[l+1]){
    					l++;
    				}
    				while(l<r && nums[r]==nums[r-1]){
    					r--;
    				}
    				l++;
    				r--;
    			}
    			else if(nums[l] + nums[r] + nums[i] < 0){
    				l++;
    			}
    			else{
    				r--;
    			}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值