题目:

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: 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和j,在j+1至n中寻找符合条件的第三个值,一种方法是建立map映射表,利用map的find函数。对重复项的检测上使用了比较麻烦的方法。

Solution 1 (TLE)

 class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> vv;
vector<int> v;
int i = , j = , n = nums.size(),tar=;
unordered_map<int, int> m;
for(; i<n; i++)
//value-position
m[nums[i]] = i;
for(i=; i<n-; i++) {
for(j=i+; j<n-; j++) {
tar = - nums[i] - nums[j];
if(m.count(tar) && m[tar]>j) {
v.push_back(nums[i]);
v.push_back(nums[j]);
v.push_back(tar);
sort(v.begin(),v.end());
if(find(vv.begin(),vv.end(),v) == vv.end())
vv.push_back(v);
v.clear();
}
}
}
return vv;
}
};

  Solution 1 TLE的原因就在于重复字段的判断上,耗费了大量时间。那么怎么降低呢?这里有个小技巧,对于存在可重复数字的数组,往往联想到先将数组排序,这样可能会减少大量工作。于是在for循环前先将nums排序,然后在循环中对于两元素值相同的情况直接跳过,即当nums[i] == nums[i-1]时,由于nums[i-1]已经遍历完成,故跳过nums[i],对于j(尾指针)也是同样的处理。

Solution 2 (312ms)

class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> vv;
vector<int> v;
int i = , j = , n = nums.size(),tar=;
unordered_map<int, int> m;
sort(nums.begin(),nums.end()); for(; i<n; i++)
//value-position
m[nums[i]] = i;
for(i=; i<n-; i++) {
if (i> && nums[i-]==nums[i]) continue;
for(j=i+; j<n-; j++) {
if (j>i+ && nums[j-]==nums[j]) continue;
tar = - nums[i] - nums[j];
if(m.find(tar) != m.end() && m[tar]>j) {
vv.push_back({nums[i],nums[j],tar});
}
}
}
return vv;
}
};

  Solution 2 虽然AC了,但用时312ms,效率太低了。我们进一步进行优化。此题的思路就是在i之后的数组内寻找符合条件的两个值,Solution 1和Solution 2是将i和j固定,寻找第三个值,那么我们也可以固定i,寻找j和k来满足条件。还是先将数组排序,固定i后,j,k分别为剩余数组的头指针、尾指针,在j<k时执行搜索,直到j>=k时停止搜索。遇到重复项依然是跳过处理。

Solution 3  (119ms)

 class Solution {
public:
vector<vector<int> > threeSum(vector<int> &nums) {
vector<vector<int>> vv;
sort(nums.begin(), nums.end());
int n = nums.size(); for(int i=; i<n-; i++) {
if(nums[i] > ) break;
if(i> && nums[i] == nums[i-]) continue;
int a = nums[i];
int j = i+, k = n-;
while(j<k) {
int b = nums[j], c = nums[k];
if(a+b+c == ) {
vv.push_back({a,b,c});
while(j<n && nums[j] == nums[j+]) j++; j++;
while(k>i && nums[k] == nums[k-]) k--; k--;
}
else if(a+b+c > ) {
while(k>i && nums[k] == nums[k-]) k--; k--;
}
else {
while(j<n && nums[j] == nums[j+]) j++; j++;
}
}
}
return vv;
}
};

  在重复项检测上也可以利用set的特性:不包含重复项。这只是一个小技巧。

Solution 4 (279ms)

class Solution {
public:
vector<vector<int> > threeSum(vector<int> &nums) {
set<vector<int>> sv;
sort(nums.begin(), nums.end());
int n = nums.size(); for(int i=; i<n-; i++) {
if(nums[i] > ) break;
int a = nums[i];
int j = i+, k = n-;
while(j<k) {
int b = nums[j], c = nums[k];
if(a+b+c == ) {
sv.insert({a,b,c});
j++;
k--;
}
else if(a+b+c > ) k--;
else j++;
}
}
return vector<vector<int>> (sv.begin(),sv.end());
}
};

【LeetCode】015 3Sum的更多相关文章

  1. 【LeetCode】15. 3Sum 三数之和

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:3sum, 三数之和,题解,leetcode, 力扣,P ...

  2. 【LeetCode】16. 3Sum Closest 最接近的三数之和

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:3sum, three sum, 三数之和,题解,lee ...

  3. 【LeetCode】923. 3Sum With Multiplicity 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/3sum-wit ...

  4. 【LeetCode】259 3Sum Smaller

    题目: Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 ...

  5. 【LeetCode】16. 3Sum Closest

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

  6. 【LeetCode】15. 3Sum 三个数和为0

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

  7. 【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 ...

  8. 【LeetCode】016 3Sum Closest

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

  9. 【leetcode】923. 3Sum With Multiplicity

    题目如下: Given an integer array A, and an integer target, return the number of tuples i, j, k  such tha ...

随机推荐

  1. Windows 下Node.js开发环境配置

    第一步:安装VirtualBox(以管理员身份安装) 1.安装完成后,打开VirtualBox,点击“新建”按钮,输入信息,“下一步”(名称可任意) 2.设置内存为1024MB,“下一步”—>“ ...

  2. windows10系统自带输入法不能切换中文如何解决

    具体如下: 1.打开计算机管理软件,右击“开始”按钮,在弹出的菜单中选择“计算机管理”: 2.或在桌面右击“此电脑”图标,在弹出的菜单中选择“管理”: 3.在打开的计算机管理软件中,选择“系统工具”- ...

  3. 实现asp.net mvc页面二级缓存,提高访问性能

    实现的mvc二级缓存的类 //Asp.Net MVC视图页面二级缓存 public class TwoLevelViewCache : IViewLocationCache { private rea ...

  4. SuperAgent使用文档

    SuperAgent是一个轻量级.灵活的.易读的.低学习曲线的客户端请求代理模块,使用在NodeJS环境中.官方文档:http://visionmedia.github.io/superagent 简 ...

  5. python login form

    import time from selenium import webdriver browser = webdriver.Chrome() wait_time = 1 USER = 'xl.fen ...

  6. Java基础 - 输出

    输出在各个开发语言中起着至关重要的作用,方便编写代码时进行调试,在java中使用 System.out.println 进行输出 public class Main { public static v ...

  7. cocos2dx使用cocostudio导出的scene

    local uilocal function createLayerUI() if not ui then ui=cc.Layer:create(); createLayerUI=nil; end r ...

  8. Js遍历对象中的属性

    var obj = {"name": "xiaol","age":"18"} for(var attr in obj){ ...

  9. js与jquey的表达

    jquery 1.$("#id").css("display") 2.$(this) 3.attr(a,b) :在a里面追加元素b 4.prop: functi ...

  10. 从分布式锁来看redis和zookpeer!

    从分布式锁来看redis和zookpeer! 目前网上大部分的基于zookpeer,和redis的分布式锁的文章都不够全面.要么就是特意避开集群的情况,要么就是考虑不全,读者看着还是一脸迷茫.坦白说, ...