3 SUM

原题:

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: 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的所有集合。

思路:

2 SUM问题的解决方法是先将数组排序,前后分别一个指针向中间逼近,时间复杂度为O(NlogN)。所以3 SUM的做法可以模仿该做法,从数组中先取一个数t,再去用2 SUM的做法去获得剩下两个加和为-t的数。

有一个最大的问题是结果去重,可以有两个方法解决,首先想到的是用set数据结构,另一种方法是遇到结果相同的数直接跳过。

代码

使用set的方法

class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
set<vector<int>> s;
for(int i = 0;i<nums.size();i++)
{
//如果第一个数已经大于0,可以不判断后面的数了,因为三个大于0的数不可能加起来等于0
if(nums[i] > 0) break;
vector<int> ans0(3,0);
ans0[0] = nums[i];
int t = 0 - nums[i];
int l = i+1, r = nums.size()-1;
while(l < r)
{
if(nums[l] + nums[r] == t)
{
ans0[1] = nums[l];
ans0[2] = nums[r];
//如果下一个数等于前一个数,跳过该数
while(l<r && nums[l+1] + nums[r] == t) l++;
while(l<r && nums[l] + nums[r+1] == t) r++;
s.insert(ans0);
l++;
r--;
}else if(nums[l] + nums[r] < t)
l++;
else
r--;
}
}
//用set构造vector
vector<vector<int>> ans(s.begin(), s.end());
return ans;
}
};

不使用set:

class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> ans;
for(int i = 0;i<nums.size();i++)
{
if(nums[i] > 0) break;
//如果下一个数和当前数相等,跳过
if(i>0 && nums[i]==nums[i-1]) continue;
vector<int> ans0(3,0);
ans0[0] = nums[i];
int t = 0 - nums[i];
int l = i+1, r = nums.size()-1;
while(l < r)
{
if(nums[l] + nums[r] == t)
{
ans0[1] = nums[l];
ans0[2] = nums[r];
//如果下一个数和当前数相等,跳过
while(l<r && nums[l+1] + nums[r] == t) l++;
while(l<r && nums[l] + nums[r+1] == t) r++;
ans.push_back(ans0);
l++;
r--;
}else if(nums[l] + nums[r] < t)
l++;
else
r--;
}
}
vector<vector<int>> ans(s.begin(), s.end());
return ans;
}
};

结果

不使用set的做法速度更快一些。

311 / 311 test cases passed.

Status: Accepted

Runtime: 49 ms

311 / 311 test cases passed.

Status: Accepted

Runtime: 109 ms

【leetcode】3 SUM的更多相关文章

  1. 【LeetCode】129. Sum Root to Leaf Numbers 解题报告(Python)

    [LeetCode]129. Sum Root to Leaf Numbers 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/pr ...

  2. 【leetcode】907. Sum of Subarray Minimums

    题目如下: 解题思路:我的想法对于数组中任意一个元素,找出其左右两边最近的小于自己的元素.例如[1,3,2,4,5,1],元素2左边比自己小的元素是1,那么大于自己的区间就是[3],右边的区间就是[4 ...

  3. 【LeetCode】633. Sum of Square Numbers

    Difficulty: Easy  More:[目录]LeetCode Java实现 Description https://leetcode.com/problems/sum-of-square-n ...

  4. 【Leetcode】404. Sum of Left Leaves

    404. Sum of Left Leaves [题目]中文版  英文版 /** * Definition for a binary tree node. * struct TreeNode { * ...

  5. 【LeetCode】Two Sum II - Input array is sorted

    [Description] Given an array of integers that is already sorted in ascending order, find two numbers ...

  6. 【leetcode】Path Sum IV

    If the depth of a tree is smaller than 5, then this tree can be represented by a list of three-digit ...

  7. 【LeetCode】Path Sum(路径总和)

    这道题是LeetCode里的第112道题.是我在学数据结构——二叉树的时候碰见的题.题目要求: 给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和 ...

  8. 【LeetCode】Maximize Sum Of Array After K Negations(K 次取反后最大化的数组和)

    这道题是LeetCode里的第1005道题. 题目描述: 给定一个整数数组 A,我们只能用以下方法修改该数组:我们选择某个个索引 i 并将 A[i] 替换为 -A[i],然后总共重复这个过程 K 次. ...

  9. 【LeetCode】404. Sum of Left Leaves 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目大意 题目大意 解题方法 递归 迭代 日期 [LeetCode] 题目地址:h ...

  10. 【LeetCode】1022. Sum of Root To Leaf Binary Numbers 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS 日期 题目地址:https://leetco ...

随机推荐

  1. 都昌 DCWriter电子病历编辑器演示文档截屏

  2. Python学习笔记(3):数据集操作-列的统一操作

    对数据库查询,将得到一个数据集: rs=AccessDB.GetData("select * from log where f_code='600259' limit 5,5") ...

  3. Entity Framework 6.x Code Frist For Oracle 实践与注意点

    Entity Framework 6.x Code Frist For Oracle 实践与注意点 开发环境 Visual Studio.net 2015/2017 Oracle 11g/12c 数据 ...

  4. android studio svn不显示问题

    今天更新android studio SDK 重启后发现SVN功能没有了,工具栏也没有了更新提交按钮,刚开始以后是SVN程序可以不行了(在我的电脑提交更新没问题)我在官网下了最新1.9.4 打开and ...

  5. 在DataTable中执行DataTable.Select("条件")返回DataTable;

    转:http://blog.csdn.net/hcf_force/article/details/7779062 1.在DataTable中执行DataTable.Select("条件&qu ...

  6. Swift中的富文本注释格式

    Apple当前启用了Markup语法形式的富文本注释格式,并且为此列出了官方文档,可以参考此链接:https://developer.apple.com/library/ios/documentati ...

  7. 将w3cplus网站中的文章页面提取并导出为pdf文档

    最近在看一些关于CSS3方面的知识,主要是平时看到网页中有很多用CSS3实现的很炫的效果,所以就打算系统的学习一下.在网上找到很多的文章,但都没有一个好的整理性,比较凌乱.昨天看到w3cplus网站中 ...

  8. 匿名对象和object的转换

    有时候经常用到需要把一个匿名对象存入session或List<object>或其他容器中,可是取出来的时候变成object了,不太方便使用. 下面是一种转换方式:     class Pr ...

  9. Android TabActivity中onKeyDown无效问题

    @Override     public boolean onKeyDown(int keyCode, KeyEvent event)     {                  //按下键盘上返回 ...

  10. 804 pretest 解题

    Answers with Explanations 1. c) s1 and s2 not equal s1 and s3 equal JVM sets a constant pool in whic ...