[Leetcode] 3sum 三数和

本文解析了给定数组中寻找三个整数使其和为零的问题,并提供了一种有效的算法解决方案。通过先排序再使用双指针技巧遍历数组,避免了重复解,实现了高效求解。

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.

 

    For example, given array S = {-1 0 1 2 -1 -4},

    A solution set is:
    (-1, 0, 1)
    (-1, -1, 2)

题意:给定值0,使三数之和等于0,返回所有情况。

思路:这题的思路和3sum closest类似。关键在于去重。代码如下:

 1 class Solution {
 2 public:
 3     vector<vector<int> > threeSum(vector<int> &num) 
 4     {
 5         vector<vector<int>> res;
 6         sort(num.begin(),num.end());
 7         if(num.size()<3)    return res;
 8 
 9         for(int i=0;i<num.size()-2;++i)
10         {
11             if(num[i]>0)   break;  //最小值大于0,返回空
12             if(i>0&&num[i]==num[i-1]) continue;   //去重
13             int l=i+1,r=num.size()-1;
14             while(l<r)
15             {
16                 int sum=num[i]+num[l]+num[r];
17                 if(sum==0)
18                 {
19                     res.push_back({num[i], num[l], num[r]});
20                     //去重
21                     while(++l<r&&num[l-1]==num[l])
22                         ;
23                     while(--r>l&&num[r]==num[r+1])
24                        ;
25                 }
26                 else if(sum<0)
27                     ++l;
28                 else
29                     r--;
30 
31             }
32         }
33         return res;    
34     }
35 };

 

转载于:https://www.cnblogs.com/love-yh/p/7108695.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值