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

本文共 1330 字,大约阅读时间需要 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)

 

  读完题目,立刻想到之前做过的Two Sum,原理相同。只是我提交的时候遇到OLE(Output Limit Exceeded),原因是输出的结果中包含重复的 triplet。

solution:

vector
> threeSum(vector
&num) { int n = num.size(); vector
> res; if(n < 3) return res; sort(num.begin(),num.end()); vector
temp(3,0); int low, high; for (int i = 0;i < n-2;++i) { low = i + 1; high = n - 1; while (low < high) { if(num[i] + num[low] + num[high] == 0) { temp[0] = num[i]; temp[1] = num[low]; temp[2] = num[high]; res.push_back(temp); ++low; --high; while (low < high && num[low] == num[low-1]) ++low; while (low < high && num[high] == num[high+1]) --high; } else if (num[i] + num[low] + num[high] < 0) ++low; else --high; } while (i+1 < n-2 && num[i+1] == num[i]) ++i; } return res;}

  想要AC,一是思路,二是细节。Fighting!!!

转载于:https://www.cnblogs.com/gattaca/p/4281581.html

你可能感兴趣的文章
足球——2011-2012德甲球队队标
查看>>
Signalr系列之虚拟目录详解与应用中的CDN加速实战
查看>>
一个简单的Linux后门程序的实现
查看>>
前端之jquery
查看>>
Java练习 SDUT-2246_时间日期格式转换
查看>>
Python中 可变参数
查看>>
python_函数传递列表
查看>>
上海市松江区 <-> 上海市金山区枫泾·万枫东路ab6177,racehttp://live.racing-china.com/...
查看>>
webpack 学习笔记 (一)
查看>>
eclipse安装spring的插件
查看>>
hide software keybox
查看>>
Linux下clock计时函数学习【转】
查看>>
0405复利5.0震撼来袭
查看>>
【软件工程】功能规格说明书
查看>>
KMP算法总结
查看>>
KOA中间件的基本运作原理
查看>>
jquery中子元素和后代元素的区别
查看>>
linux环境下搭建solr服务器--单机版
查看>>
可图的度序列判断与构造
查看>>
VUE1)搭建VUE脚手架
查看>>