Given an array nums of n integers, are there elements abc in nums 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

排序 + 双指针
本题的难点在于如何去除重复解。

算法流程:
特判,对于数组长度 nn,如果数组为 nullnull 或者数组长度小于 33,返回 [][]。
对数组进行排序。
遍历排序后数组:
若 nums[i]>0nums[i]>0:因为已经排序好,所以后面不可能有三个数加和等于 00,直接返回结果。
对于重复元素:跳过,避免出现重复解
令左指针 L=i+1L=i+1,右指针 R=n-1R=n−1,当 L<RL<R 时,执行循环:
当 nums[i]+nums[L]+nums[R]==0nums[i]+nums[L]+nums[R]==0,执行循环,判断左界和右界是否和下一位置重复,去除重复解。并同时将 L,RL,R 移到下一位置,寻找新的解
若和大于 00,说明 nums[R]nums[R] 太大,RR 左移
若和小于 00,说明 nums[L]nums[L] 太小,LL 右移

 class Solution {
public:
vector<vector<int>> threeSum(vector<int>& a) {
const int n = a.size();
vector<vector<int>> res;
if (n < ) return res;
std::sort(a.begin(),a.end());
for(int i = ; i < n; ++i) {
if (i!= && a[i]==a[i-]) continue;
int low = i+;
int high = n-;
while(low < high) {
if(a[low]+a[high]>-a[i]) {
high--;
} else if(a[low]+a[high]<-a[i]){
low++;
} else {
std::vector<int> res_tmp = {a[i],a[low],a[high]};
res.emplace_back(res_tmp); while (low < high && a[low]==a[low+]) {
low++;
}
while (low < high && a[high]==a[high-]) {
high--;
}
low++;
high--;
}
}
}
return res;
}
};

借助 2sum中字典的应用。  时间复杂度 o(n**2)
 class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) < 3:
return []
nums.sort()
res = set()
for i, v in enumerate(nums[:-2]):
d = {}
for x in nums[i+1:]:
if x not in d:
d[-v-x] = 1
else:
res.add((v, -v-x, x))
return map(list, res)

15. 3Sum(字典)的更多相关文章

  1. LeetCode 15 3Sum [sort] <c++>

    LeetCode 15 3Sum [sort] <c++> 给出一个一维数组,找出其中所有和为零的三元组(元素集相同的视作同一个三元组)的集合. C++ 先自己写了一发,虽然过了,但跑了3 ...

  2. 1. Two Sum&&15. 3Sum&&18. 4Sum

    题目: 1. Two Sum Given an array of integers, return indices of the two numbers such that they add up t ...

  3. leetcode 1.Two Sum 、167. Two Sum II - Input array is sorted 、15. 3Sum 、16. 3Sum Closest 、 18. 4Sum 、653. Two Sum IV - Input is a BST

    1.two sum 用hash来存储数值和对应的位置索引,通过target-当前值来获得需要的值,然后再hash中寻找 错误代码1: Input:[3,2,4]6Output:[0,0]Expecte ...

  4. leetcode 15. 3Sum 二维vector

    传送门 15. 3Sum My Submissions Question Total Accepted: 108534 Total Submissions: 584814 Difficulty: Me ...

  5. 15. 3Sum、16. 3Sum Closest和18. 4Sum

    15 3sum Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = ...

  6. 刷题15. 3Sum

    一.题目说明 题目非常简洁15. 3Sum,读懂题目后,理解不难. 但 实话说,我们提交代码后,Time Limit Exceeded,最主要的是给了非常长的测试用例,我本地运行后87秒,确实时间非常 ...

  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 all un ...

  8. LeetCode 15. 3Sum 16. 3Sum Closest 18. 4Sum

    n数求和,固定n-2个数,最后两个数在连续区间内一左一右根据当前求和与目标值比较移动,如果sum<target,移动较小数,否则,移动较大数 重复数处理: 使i为左至右第一个不重复数:while ...

  9. 15. 3Sum C++

    参考资料: https://leetcode.com/problems/3sum/discuss/7402/Share-my-AC-C%2B%2B-solution-around-50ms-O(N*N ...

随机推荐

  1. [daily] SNAT和DNAT

    SNAT,DNAT,MASQUERADE都是NAT MASQUERADE是SNAT的一个特例 SNAT是指在数据包从网卡发送出去的时候,把数据包中的源地址部分替换为指定的IP,这样,接收方就认为数据包 ...

  2. [math][mathematica] mathematica入门

    快速入门手册: 只找到了个中文的快速入门: https://www.wolfram.com/language/fast-introduction-for-programmers/zh/?source= ...

  3. [troubleshoot][archliunx][chromium][flash] chrome提示flash不是最新

    最近chrome总是在提示flash不是最新要求更新. 原来以前用的flash包 chromium-pepper-flash 不见了,改名变成了pepper-flash. /home/tong [to ...

  4. LeetCode 566 Reshape the Matrix 解题报告

    题目要求 In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a ...

  5. idea+maven+springboot+mybatis+springmvc+shiro

    springboot就是把创建项目简单化,省去了以往的配置mybatis.springmvc的繁琐过程. 搭建web应用三个主要功能,请求和响应,数据库交互,权限配置. 一.idea创建项目 (1) ...

  6. C# 解构

    我们以前用ref或者out在一定程度上可以解决方法只有一个返回值的问题.在C#7.0中新增了一个新元组(ValueTuple),他可以让我们返回多个值.话不多说,先上代码: 我们可以看到可以用隐式推断 ...

  7. caffe编译报错解决

    添加ssd中的一些层之后,编译报错: ../lib/libcaffe.so.1.0.0-rc5:对‘boost::match_results<__gnu_cxx::__normal_iterat ...

  8. caffe 测试时间报错 Aborted at unix time

    今天测试时间报错,具体如下图: 在网上查了一下,大概的原因是由于程序中使用了随机函数造成的,后来检查了一下prototxt中有可能含有随机数的地方,去掉之后就可以了,包括shuffle:true,以及 ...

  9. Redis入门到高可用(三)——通用命令

    通用命令  参考 http://redisdoc.com/index.html 1. keys  #查看所有key 时间复杂度:O(N), N 为数据库中 key 的数量. 127.0.0.1:637 ...

  10. AOP 入门

    1,源码 Application.java package com.bf; import org.springframework.context.ApplicationContext; import ...