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. Appium - iOS Mac环境结构

    Appium - iOS Mac环境结构 笔者: Max.Bai 时间: 2014/10 1. iOS开发环境的搭建 1.1系统要求 MacOS X 10.7 or higher, 10.9.2 re ...

  2. UVa 10012 - How Big Is It? 堆球问题 全排列+坐标模拟 数据

    题意:给出几个圆的半径,贴着底下排放在一个长方形里面,求出如何摆放能使长方形底下长度最短. 由于球的个数不会超过8, 所以用全排列一个一个计算底下的长度,然后记录最短就行了. 全排列用next_per ...

  3. 操作系统学习笔记_12_I/O管理 --I/O管理概述

    h1 { margin-bottom: 0.21cm; }h1.western { font-family: "Liberation Sans",sans-serif; font- ...

  4. 于ubuntu配置hadoop当问题

    1. 构造ssh登录 我们并不需要改变/etc/ssh/sshd_config 2. 新hadoop用户,home下列不hadoop夹 创建使用下面的命令 useradd -m hadoop 3. n ...

  5. Android对于静默安装和卸载

    在一般情况下,Android系统安装apk会有一个安装界面,用户可以单击确定或取消apk设备. 但在实际的项目需求中,有一种需求.就是希望apk在后台安装(不出现安装界面的提示),这样的安装方式称为静 ...

  6. 使用C++实现功能下载文件

    今天问一个同学C++实现的下载链接下载并保存给定的文件,互联网搜索.看到这样的事情在网上.因此,改变下直接带来,因为他的代码是在VC++,我导入到VS2010中出现点小问题.所以改了下贴了个VS中亲測 ...

  7. groovy install,gvm,groovysh简述(转)

    1.1 安装Groovy Groovy主页:http://www.groovy-lang.org 确保本地系统安装了Java 1.1.1 在Windows系统上安装Groovy 1.创建环境变量GRO ...

  8. windows平台下载android源代码

    最近观看<android核心分析>,所以很多细节都没有详细看代码很难理解.请记住,印象不深.感觉是最好再一起去的源代码,返回下载android源代码,遇到了许多问题,最后开始下载.合并流程 ...

  9. 让UIAlertController兼容的同时iphone和ipad

    让UIAlertController兼容的同时iphone和ipad by 吴雪莹 var alert = UIAlertController(title: nil, message: message ...

  10. 于ios7在遇到一些发展deprecated问题

    cell.textLabel.textAlignment = UITextAlignmentCenter; 现在我想写cell.textLabel.textAlignment =NSTextAlign ...