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. boostrap-非常好用但是容易让人忽略的地方------Font Awesome

    font-awesome基本用法 官方代码传送门 font-awesome在bootstrap中的特殊用法(这个才是重点) 要点归纳1(官方) 官方代码传送门 要点归纳2(我的) <a href ...

  2. SQL开发中容易忽视的一些小地方( 三)

    原文:SQL开发中容易忽视的一些小地方( 三) 目的:这篇文章我想说说我在工作中关于in和union all 的用法. 索引定义 : 微软的SQL SERVER提供了两种索引:聚集索引(cluster ...

  3. [Unity3D]Unity3D圣骑士当游戏开发商遭遇Mecanim动画系统

            大家好.我是秦培.欢迎关注我的博客.我的博客地址blog.csdn.net/qinyuanpei. 博主总算赶在这个月底写出了这篇文章.这个月由于期末考试一直没时间研究太多关于技术方面 ...

  4. 【剑指offer】最大和连续子阵列

    个開始,到第3个为止).你会不会被他忽悠住? 输入: 输入有多组数据,每组測试数据包括两行. 第一行为一个整数n(0<=n<=100000),当n=0时,输入结束.接下去的一行包括n个整数 ...

  5. Model-View-Presenter(MVP)

    Model-View-Presenter(MVP)模式 Model-View-Presenter(MVP)是一种应用程序表示层的设计模式.该设计模式最早于90年代由Taligent提出,并率先在C++ ...

  6. cocos2d-x 网络请求

    [cocos2dx]rapidjson用法以及中文显示的解决方法 cocos2dx 读取json及解析 cocos2dx rapidjson 高速解析JSON  --- [cocos2d-x官方文档] ...

  7. express: command not found.

    npm install -g express 可是不行.全局模式不行. With the release of Express 4.0.0 it looks like you need to do s ...

  8. Ubuntu 14.04 grub2 温馨提示

    昨天win7在...的基础上,刚装几天发布Ubuntu14.04.Ubuntu14.04还是很不错的.但是,今天想去下一个Win7,但没有发现平时的开机显示grub2选项,直接进了Ubuntu! 我感 ...

  9. Ubuntu 当黑屏解决方案安装

    前几天我就已经安装Red hat 企业版,只是可惜它并没有提供数据源.我能够安装自己的软件,但我不能完全靠解决,因此,我们决定改变系统,最后我选择ubuntu.随时下载系统.然后用u盘制作启动盘,全部 ...

  10. Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Multiple representations of the same entity解决方法

    1.错误信息 Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUs ...