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. FreeSwitch安装配置记录

    安装FreeSwitch 主要命令如下: git clone -b v1.2.stable git://git.freeswitch.org/freeswitch.gitcd freeswitch/. ...

  2. navigationBar设置透明

    //设置全透明方式 一.完全不用图片(iOS7之后有效)[self.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBar ...

  3. 安卓App流量统计

    http://keepcleargas.bitbucket.org/2013/10/12/android-App-Traffic.html 安卓App流量统计 12 OCT 2013 android流 ...

  4. LM-Sensors unable to load driver module

    Fix - sort of - for LM-Sensors unable to load driver module In short: In /etc/default/grub set GRUB_ ...

  5. IrregularGridCollectionView处理不定宽度的标签cell

    IrregularGridCollectionView处理不定宽度的标签cell 效果 源码 https://github.com/YouXianMing/UI-Component-Collectio ...

  6. AngularJS 中的 Promise 和 设计模式(转)

    原文地址:http://my.oschina.net/ilivebox/blog/293771 目录[-] Promise 简单例子 链式 Promise Parallel Promises And ...

  7. nginx+tomcat+java部署总结

    昨天部署了一下nginx+tomcat+java出现了很多问题,以下为整理总结. 使用了两种部署方式,一种是源码部署,一种是war部署. java源码部署总结: 环境:nginx+tomcat 部署方 ...

  8. 北京地铁月度消费总金额计算(Python版)

    最近业余时间在学习Python,这是那天坐地铁时突发奇想,想看看我这一个月的地铁费共多少钱,所以简单的构思了下思路,就直接开写了,没想到用Python来实现还挺简单的. 设计思路: 每次乘车正常消费7 ...

  9. emoji和utf8mb4字符集

    mysql 的 utf8 不支持 emoji,需要修改设置为utf8mb4 <?php 'mysql' => [ 'charset' => 'utf8mb4', 'collation ...

  10. 关于Unity程序在IOS和Android上显示内嵌网页的方式

    近期因为有须要在Unity程序执行在ios或android手机上显示内嵌网页.所以遍从网上搜集了一下相关的资料.整理例如以下: UnityWebCore 从搜索中先看到了这个.下载下来了以后发现这个的 ...