Problem:

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) 先说说我的思路吧。先排序。我也不知道为什么莫名其妙的想到固定中间一个数的方法。i从第二个开始一直到倒数第二个数,然后left从i的左边一个开始,right从i的右边一个开始,如果三个数相加大于零,那么肯定就要left往左,如果相加小于零那就right往右,如果等于零,再判断是否与已经存入sum中的最后一个判断比较不相等就写入。现在就碰到了以前没有碰到过的问题,不是Time Limit Exceeded,而是Output Limit Exceeded。查了下说,这个问题应该是while循环没有出来。但是我看了以下代码,没有理由没跳出来啊。
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num)
{
bool flag = false;
vector<vector<int> > sum;
vector<int> temp = num;
sort(temp.begin(), temp.end());
if (num.size() < || temp[] > )
return sum; for (int i = ; i != num.size() - ; i++)
{
int left = i - , right = i + ;
while(left>= && right < num.size())
{
if (temp[left] + temp[i] + temp[right] == )
{
vector<int> sub;
sub.push_back(temp[left]);
sub.push_back(temp[i]);
sub.push_back(temp[right]);
if (!flag)
{
flag = true;
sum.push_back(sub);
}
else if(sub != sum[sum.size()-])
{
sum.push_back(sub);
}
left--;
right++;
}
else if(temp[left] + temp[i] + temp[right] < )
{
right++;
}
else
left--;
}
}
sum.erase(unique(sum.begin(), sum.end()), sum.end());
return sum;
}
};

后来请实验室的大牛(可能要去Google工作了)看了下。说应该是内存不够了。就是还是存了相同的例子。单单用判断是不是等于sum的最后一个是否相等是不行的。应该是这样,OJ里测试的时候估计给了sum的大小有限。如果重复了那就Output Limit了。其实我差成功只是一小步了。

以下代码是固定三个数的第一个,然后i从第一个到倒数第三个就行了。如果i往前移动的时候和前一个数相等那就不用再判断了,直接i++,因为以该数开头的三元组都已经计算过并存起来了。其中还有一个很好的地方就是在判断三元组是不是第一个的时候,用的是sum.size()==0 || sum.size() > 0 ...这个很好,因为第一次的时候是==0的,那||之后的就不作判断了。下一次的时候size不==0.再做后面的判断,后面的判断是因为三个数只要有两个数相等那第三个肯定也相等。代码如下。

class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
vector<vector<int> > sum;
if(num.size()<)
return sum;
sort(num.begin(),num.end());
int k = ;
for(int i = ;i<num.size()-;i++)
{
if(i> && num[i] == num[i-])
continue;
int j = i+; if(num[i]+num[j]>)
break;
k = num.size()-;
while(j<k)
{
if(num[i]+num[j]+num[k] == )
{
if(sum.size()== || sum.size()> && !(num[i]==sum[sum.size()-][]&& num[j] ==sum[sum.size()-][] ))
{
vector<int> ansPiece;
ansPiece.push_back(num[i]);
ansPiece.push_back(num[j]);
ansPiece.push_back(num[k]);
sum.push_back(ansPiece);
}
}
if(num[i]+num[j]+num[k] < )
j++;
else
k--;
}
}
return sum;
}
};

2015/4/3:

class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
sort(num.begin(), num.end());
vector<vector<int> > ans;
for (int i = ; i < num.size(); i++){
int target = - * num[i];
if (i > && num[i] == num[i-])
continue;
int left = i + , right = num.size() - ;
while (left < right){
if (target == num[left] + num[right]){
vector<int> tmp;
tmp.push_back(num[i]);
tmp.push_back(num[left]);
tmp.push_back(num[right]);
ans.push_back(tmp);
while(left < num.size() && num[left] == tmp[])
left++;
while(right > && num[right] == tmp[])
right--;
}
else if (target > num[left] + num[right])
left++;
else
right--;
} }
return ans;
}
};

leetcode第15题--3Sum的更多相关文章

  1. LeetCode第[15]题(Java):3Sum 标签:Array

    题目难度:Medium 题目: Given an array S of n integers, are there elements a, b, c in S such that a + b + c  ...

  2. LeetCode第[15]题(Java):3Sum (三数之和为目标值)——Medium

    题目难度:Medium 题目: Given an array S of n integers, are there elements a, b, c in S such that a + b + c  ...

  3. [LeetCode][Python]15:3Sum

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 15: 3Sumhttps://oj.leetcode.com/problem ...

  4. leetcode:1-5题代码整理

    以下是这段时间抽时间刷的前5题,都是自己想的解法,或许不是最优解,只是整理下,方便日后优化提升 1. Two Sum: class Solution: # @return a tuple, (inde ...

  5. leetcode第16题--3Sum Closest

    Problem:Given an array S of n integers, find three integers in S such that the sum is closest to a g ...

  6. LeetCode题解 15题 第二篇

    之前写过一篇,这是第二篇.上一篇用了多种编程语言来做,这一次是以学算法为主,所以打算都用python来完成. 4. Median of Two Sorted Arrays There are two ...

  7. leetcode第15题:三数之和

    给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中不可以包含重复的三元组. ...

  8. LeetCode(15) 3Sum

    题目 Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all ...

  9. LeetCode(15)3Sum

    题目如下: Python代码: def threeSum(self, nums): res = [] nums.sort() for i in xrange(len(nums)-2): if i &g ...

随机推荐

  1. android变化HOLO对话风格

    andriod风修改对话框格,通过设置theme实现.一些要素需要通过Java代码更改,下面的对话框更改的步骤的例子称号. 1.写文本样式. DIALOG标题是textview,在sytles.xml ...

  2. [SignalR]注册路由

    原文:[SignalR]注册路由 1.注册SignalR路由 在Asp.Net中,若是SignalR 1.*版本,在Global.asax文件中定义如下: 在Asp.Net中,若是SignalR 2. ...

  3. CORS

    CORS(跨域资源共享) 前言:上一篇文章提到使用JSONP实现跨域请求的时候,偶然间提到CORS,即Cross-Origin Resource Sharing(跨域资源共享).虽然前些天也看了一下, ...

  4. JS前端正则表达式学习笔记(转)

    1.正则表达式的创建: 方法一:以字面量形式来创建 格式为/pattern/flags;其中pattern(模式)为任何简单或者复杂的表达式,可以包括字符类,限定符,分组,向前查找以及反向引用.每个正 ...

  5. hdu4288 Coder 2012成都网络赛 A题

    题意:往集合里面添加删除数,集合中的数是按从小到大排列的,询问下标模5等于3的数的和. 记得当时这题不会做, 现在想简单多了,只要维护五个值和左右子树的size大小就行了. #define maxn ...

  6. java多线程(同步和死锁,生产者和消费者问题)

    首先我们来看看同步与死锁: 所谓死锁.这是A有banana,B有apple. A至B说:你把apple对我来说,,我会banana给你. B至A说:你把banana对我来说,,我会apple给你. 可 ...

  7. find your present (2) 2095

    Problem Description In the new year party, everybody will get a "special present".Now it's ...

  8. JS常用方法总结,及jquery异步调用后台方法实例

    //前台接收get参数值 function getQueryString(name) {            var queryStrings = window.location.search.sp ...

  9. 程序员的Scala

    C#程序员的Scala之路第九章(Scala的层级) 摘要: 1.Scala的类层级Scala里类的顶端是Any所有的类都继承Any类,Any包括以下几个通用方法:final def ==(that: ...

  10. 关于tasklet的一点小小的解释

    大概有一些同学对tasklet的串行化还有点困惑,其实在单处理器上最好理解,所以本帖主要讨论多处理器上tasklet如何实现串行化:同一个tasklet对象同一时刻只能在一个处理器上运行. 在 驱动程 ...