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:

  1. Given array nums = [-1, 0, 1, 2, -1, -4],
  2.  
  3. A solution set is:
  4. [
  5. [-1, 0, 1],
  6. [-1, -1, 2]
  7. ]

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

算法流程:
特判,对于数组长度 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 右移

  1. class Solution {
  2. public:
  3. vector<vector<int>> threeSum(vector<int>& a) {
  4. const int n = a.size();
  5. vector<vector<int>> res;
  6. if (n < ) return res;
  7. std::sort(a.begin(),a.end());
  8. for(int i = ; i < n; ++i) {
  9. if (i!= && a[i]==a[i-]) continue;
  10. int low = i+;
  11. int high = n-;
  12. while(low < high) {
  13. if(a[low]+a[high]>-a[i]) {
  14. high--;
  15. } else if(a[low]+a[high]<-a[i]){
  16. low++;
  17. } else {
  18. std::vector<int> res_tmp = {a[i],a[low],a[high]};
  19. res.emplace_back(res_tmp);
  20.  
  21. while (low < high && a[low]==a[low+]) {
  22. low++;
  23. }
  24. while (low < high && a[high]==a[high-]) {
  25. high--;
  26. }
  27. low++;
  28. high--;
  29. }
  30. }
  31. }
  32. return res;
  33. }
  34. };
  1.  
  2. 借助 2sum中字典的应用。 时间复杂度 o(n**2)
  1. class Solution(object):
  2. def threeSum(self, nums):
  3. """
  4. :type nums: List[int]
  5. :rtype: List[List[int]]
  6. """
  7. if len(nums) < 3:
  8. return []
  9. nums.sort()
  10. res = set()
  11. for i, v in enumerate(nums[:-2]):
  12. d = {}
  13. for x in nums[i+1:]:
  14. if x not in d:
  15. d[-v-x] = 1
  16. else:
  17. res.add((v, -v-x, x))
  18. 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][qemu][kvm] 使用virtfs在host与guest之间共享目录

    如题. 之前我使用NFS,NFS会有同步问题.比如编译文件时候的时间同步问题,见前边的文章. 如今,我们使用高级的virtfs: 见:https://www.linux-kvm.org/page/9p ...

  2. day4_修改文件

    修改文件有两种方式:一种是把文件的全部内容都读到内存中,然后把原有的文件内容清空,重新写新的内容:第二种是把修改后的文件内容写到一个新的文件中 第一种:一次性把文件全部读到,读到内存这个能,这种文件小 ...

  3. linux 搭建ftp服务

    一. 安装ftp yum -y install vsftpd 二.配置 安装完之后在/etc/vsftpd/路径下会存在三个配置文件. vsftpd.conf: 主配置文件 ftpusers: 指定哪 ...

  4. 前端 HTML body标签相关内容 常用标签 表单标签 form

    表单标签 form 表单是一个包含表单元素的区域表单元素是允许用户在表单中输入内容,比如:文本域(textarea).输入框(input).单选框() 表单的作用 form标签作用是把用户输入数据信息 ...

  5. 数据库——MongoDB增删改查

    MongoDB增删改查操作 本文包含对数据库.集合以及文档的基本增删改查操作 数据库操作 #1.增 use config #如果数据库不存在,则创建并切换到该数据库,存在则直接切换到指定数据库. #2 ...

  6. what' the python之面向对象(进阶)

    面向对象的知识点补充(进阶版) classmethod和staticmethod:这两个函数的用途就是可以不用实例化对象就可以调用方法 class Classmethod_Demo(): role = ...

  7. 多周期MACD趋势共振制作的方法

    我浏览了创幻论坛.理想论坛,来到MACD股市技术分析俱乐部,真正找到自己的乐土. 做人要厚道!指标之王MACD既然被先辈们创造了出来,就应由我辈发扬光大!自吹自擂者.吝啬者都应自觉退出论坛既然来到这里 ...

  8. os.path的使用

    os.path 1.返回当前目录 举个例子: (1)给出一个目录名称,返回绝对路径 project_path = "Exercise" path = os.path.dirname ...

  9. element-dialog封装成子组件

    1.父组件 <template> <card-layout :title="L('Users')" :actions="actions" @c ...

  10. js中的offsetLeft和style.left

    (1)style.left是带单位"px"的,而offsetLeft没有单位,另外,style.left必须是内联样式,或者在JS中通过style.left赋值,否则取得的将为空字 ...