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. [性能优化] perf

    运行时性能分析工具 wiki:https://en.wikipedia.org/wiki/Perf_(Linux) linux wiki:https://perf.wiki.kernel.org/in ...

  2. BTree和B+Tree详解

    https://www.cnblogs.com/vianzhang/p/7922426.html B+树索引是B+树在数据库中的一种实现,是最常见也是数据库中使用最为频繁的一种索引.B+树中的B代表平 ...

  3. idea tomcat控制台system.out.println是乱码

    配置一下tomcat的信息.然后设置VM options.添加:-Dfile.encoding=UTF-8

  4. pillow与numpy实现图片素描化

    from PIL import Image import numpy as np #封装一个图像处理类 class TestNumpy(object): def photo2paint(self,im ...

  5. golang 死锁

    golang中for{}会引起程序死锁 如: main(){ go func(){fmt.Println("dfkdsf")} for{ } } 程序运行一会会停止 按照下面的写法 ...

  6. TZOJ 5225: 玩转二叉树

    描述 给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列.所谓镜面反转,是指将所有非叶结点的左右孩子对换.这里假设键值都是互不相等的正整数. 输入 输入第一行给出 ...

  7. magento开发手册之目录结构

    magento是一个很优秀的电商系统,很多朋友会用它部署自己的电商网站,少不了二次开发.下面我们随着ytkah来一起认识一下magento开发手册之目录结构吧. /app – 程序根目录 /app/e ...

  8. Linux-eth0 eth0:1 ifcfg-lo ifcfg-lo:0 和eth0.1关系、ifconfig以及虚拟IP实现介绍

    eth0 eth0:1 和eth0.1三者的关系对应于物理网卡.子网卡.虚拟VLAN网卡的关系:物理网卡:物理网卡这里指的是服务器上实际的网络接口设备,这里我服务器上双网卡,在系统中看到的2个物理网卡 ...

  9. 前端框架之Vue(4)-Class与Style绑定

    操作元素的 class 列表和内联样式是数据绑定的一个常见需求.因为它们都是属性,所以我们可以用 v-bind 处理它们:只需要通过表达式计算出字符串结果即可.不过,字符串拼接麻烦且易错.因此,在将  ...

  10. vue-自定义pc端键盘-动画

    <template> <div class="keyboard"> <div class="keyboard_key"> & ...