博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode] 3Sum
阅读量:7294 次
发布时间:2019-06-30

本文共 1215 字,大约阅读时间需要 4 分钟。

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的时候,要注意第二个数或者第三个数要变化一下,否则就会陷入死循环中。

题解:

class Solution {public:    vector
> threeSum(vector
&num) { vector
> res; vector
tmp; sort(num.begin(), num.end()); for(int i=0;i
0 && num[i]==num[i-1]) i++; int l = i+1; int r = num.size()-1; while(l
i+1 && num[l]==num[l-1]) l++; while(r
0) r--; else if(sum<0) l++; else { tmp.clear(); tmp.push_back(num[i]); tmp.push_back(num[l]); tmp.push_back(num[r]); res.push_back(tmp); l++; } } } } return res; }};
View Code

 

 

 

 

转载于:https://www.cnblogs.com/jiasaidongqi/p/4191424.html

你可能感兴趣的文章
加载某个页面(A)时实现自动跳转到某个页面(B)
查看>>
Jenkins入门系列之——03PDF文档下载
查看>>
Digit Generator(生成元)
查看>>
php 入门笔记
查看>>
Python3.7安装PyQt5的方法
查看>>
Zoj 3781(构造)
查看>>
One error related to msxml4.dll (0x800C0014)
查看>>
“爆打”团队阿尔法发布 以及 第四周任务
查看>>
【堆】bzoj1293 [SCOI2009]生日礼物
查看>>
JavaScript的异步运行机制
查看>>
centos7安装HTTPS协议
查看>>
GNS3 模拟icmp端口不可达
查看>>
hdu 5677 ztr loves substring 多重背包
查看>>
WCF学习
查看>>
django 基础进 COOKIE
查看>>
[Java 8] (10) 使用Lambda完成函数组合,Map-Reduce以及并行化
查看>>
@EnableWebMvc
查看>>
eclipse中输入的中文为繁体的问题
查看>>
.NET跨平台:在Linux Ubuntu上编译coreclr/corefx/dnx(20150617)
查看>>
[CQOI2016]手机号码
查看>>