LeetCode:两数之和、三数之和、四数之和

利用哈希集合减少时间复杂度及双指针收缩窗口的巧妙解法

No.1 两数之和

题目:

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素

示例:

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

解法:

  1. 穷举所有组合

    时间复杂度:\(O(n^2)\),两次循环

    空间复杂度:\(O(1)\)

    两层循环,判断每一种组合

  2. 利用哈希减少时间复杂度

    时间复杂度:\(O(n)\),一层循环\(O(n)\) * 哈希查找\(O(1)\)

    空间复杂度:\(O(n)\),哈希表最多存 n 个元素

    将数组元素存入哈希表,查找对应目标元素是否在数组中

    对于每个元素,查找后面是否有目标元素

    public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++)
    map.put(nums[i], i);
    for (int i = 0; i < nums.length; i++) {
    int j = target - nums[i];
    if (map.containsKey(j) && map.get(j) != i) {
    return new int[] { i, map.get(j) };
    }
    }
    return new int[]{};
    }

    优化,用一次循环解决问题。对于每个元素,查找前面是否有目标元素

    public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
    int j = target - nums[i];
    if (map.containsKey(j) && map.get(j) != i) {
    return new int[]{i, map.get(j)};
    }
    map.put(nums[i], i);
    }
    return new int[]{};
    }

    Map 存入相同元素会被覆盖,本题中并不影响结果

No.15 三数之和

题目:

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组

注意:答案中不可以包含重复的三元组

示例:

给定数组 nums = [-1, 0, 1, 2, -1, -4]
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]

解法:

  1. 穷举所有组合

    时间复杂度:\(O(n^3)\),三重循环\(O(n^3)\)

    空间复杂度:\(O(1)\)

    三层循环,判断所有组合,去重

  2. 利用哈希表减少时间复杂度

    时间复杂度:\(O(n^2)\),排序 \(O(nlogn)\) + 两重循环 \(O(n^2)\) * 哈希查找 \(O(1)\)

    空间复杂度:\(O(n)\)

    先进行排序,有利于后面去重

    两层循环,判断目标值是否在数组中,并且保证在后方数据中查找,以免造成重复

    public List<List<Integer>> threeSum(int[] nums) {
    List<List<Integer>> lists = new ArrayList<>();
    if (nums.length < 3) return lists;
    Arrays.sort(nums);//排序
    HashMap<Integer, Integer> map = new HashMap<>();
    for (int i=0;i<nums.length;i++)
    map.put(nums[i],i);
    for (int i = 0; i < nums.length - 2; i++) {
    if (i > 0 && nums[i] == nums[i - 1]) continue;//去重
    for (int j = i + 1; j < nums.length; j++) {
    if (j > i + 1 && nums[j] == nums[j - 1]) continue;//去重
    int a = nums[i];
    int b = nums[j];
    int c = -a - b;
    if (map.containsKey(c) && map.get(c) > j) {//向后查找
    lists.add(new ArrayList<Integer>() {{
    add(a);
    add(b);
    add(c);
    }});
    } else continue;
    }
    }
    return lists;
    }
  3. 利用数据特点,双指针收缩窗口

    时间复杂度:\(O(n^2)\)

    空间复杂度:\(O(1)\)

    先进行排序,有利于去重

    三元组 [ k,i,j ],每一个 k,i = k+1,j = length-1

    求和,大于 0 ,j 右移,小于 0,i 左移,等于 0,存入 List

    public List<List<Integer>> threeSum(int[] nums) {
    List<List<Integer>> lists = new ArrayList<>();
    if (nums.length < 3) return lists;
    Arrays.sort(nums);//排序
    for (int k = 0; k < nums.length - 2; k++) {
    if (k > 0 && nums[k] == nums[k - 1]) continue;//去重
    int i = k + 1, j = nums.length - 1;
    while (i < j) {
    int sum = nums[k] + nums[i] + nums[j];
    if (sum < 0) i++;
    else if (sum > 0) j--;
    else {
    List<Integer> list = new ArrayList<>();
    list.add(nums[k]);
    list.add(nums[i]);
    list.add(nums[j]);
    lists.add(list);
    while (i < j && nums[i] == nums[i + 1]) i++;//去重
    while (i < j && nums[j] == nums[j - 1]) j--;//去重
    i++;
    j--;
    }
    }
    }
    return lists;
    }

No.18 四数之和

题目:

给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组

注意:答案中不可以包含重复的四元组

示例:

给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0
满足要求的四元组集合为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]

解法:

  1. 利用哈希表减少时间复杂度

    时间复杂度:\(O(n^3)\),两重循环 \(O(n^3)\) * 哈希查找 \(O(1)\)

    空间复杂度:\(O(n)\)

    public List<List<Integer>> fourSum(int[] nums, int target) {
    List<List<Integer>> lists = new ArrayList<>();
    if (nums.length < 4) return lists;
    Arrays.sort(nums);
    HashMap<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++)
    map.put(nums[i], i);
    for (int i = 0; i < nums.length - 2; i++) {
    if (i > 0 && nums[i] == nums[i - 1]) continue;//去重
    for (int j = i + 1; j < nums.length - 1; j++) {
    if (j > i + 1 && nums[j] == nums[j - 1]) continue;//去重
    for (int k = j + 1; k < nums.length; k++) {
    if (k > j + 1 && nums[k] == nums[k - 1]) continue;//去重
    int a = nums[i];
    int b = nums[j];
    int c = nums[k];
    int d = target - a - b - c;
    if (map.containsKey(d) && map.get(d) > k) {//向后查找
    lists.add(new ArrayList<Integer>() {{
    add(a);
    add(b);
    add(c);
    add(d);
    }});
    } else continue;
    }
    }
    }
    return lists;
    }
  2. 利用数据特点,双指针收缩窗口

    时间复杂度:\(O(n^3)\),三重循环\(O(n^3)\)

    空间复杂度:\(O(n)\)

    public List<List<Integer>> fourSum(int[] nums, int target) {
    List<List<Integer>> lists = new ArrayList<>();
    if (nums.length < 4) return lists;
    Arrays.sort(nums);
    for (int a = 0; a < nums.length - 3; a++) {
    if (a > 0 && nums[a] == nums[a - 1]) continue;//去重
    for (int b = a + 1; b < nums.length - 2; b++) {
    if (b > a + 1 && nums[b] == nums[b - 1]) continue;//去重
    int c = b + 1, d = nums.length - 1;
    while (c < d) {
    int sum = nums[a] + nums[b] + nums[c] + nums[d];
    if (sum < target) c++;
    else if (sum > target) d--;
    else {
    List<Integer> list = new ArrayList<>();
    list.add(nums[a]);
    list.add(nums[b]);
    list.add(nums[c]);
    list.add(nums[d]);
    lists.add(list);
    while (c < d && nums[c] == nums[c + 1]) c++;//去重
    while (c < d && nums[d] == nums[d - 1]) d--;//去重
    c++;
    d--;
    }
    }
    }
    }
    return lists;
    }

LeetCode:两数之和、三数之和、四数之和的更多相关文章

  1. 【leetcode 简单】第三题 回文数

    判断一个整数是否是回文数.回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数. 示例 1: 输入: 121 输出: true 示例 2: 输入: -121 输出: false 解释: 从左向 ...

  2. [LintCode/LeetCode]——两数和、三数和、四数和

    LintCode有大部分题目来自LeetCode,但LeetCode比较卡,下面以LintCode为平台,简单介绍我AC的几个题目,并由此引出一些算法基础. 1)两数之和(two-sum) 题目编号: ...

  3. 【LeetCode】18、四数之和

    题目等级:4Sum(Medium) 题目描述: Given an array nums of n integers and an integer target, are there elements ...

  4. 【算法训练营day7】LeetCode454. 四数相加II LeetCode383. 赎金信 LeetCode15. 三数之和 LeetCode18. 四数之和

    [算法训练营day7]LeetCode454. 四数相加II LeetCode383. 赎金信 LeetCode15. 三数之和 LeetCode18. 四数之和 LeetCode454. 四数相加I ...

  5. [LeetCode] 454. 4Sum II 四数之和II

    Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such t ...

  6. LeetCode:四数之和【18】

    LeetCode:四数之和[18] 题目描述 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c ...

  7. 【LeetCode】 454、四数之和 II

    题目等级:4Sum II(Medium) 题目描述: Given four lists A, B, C, D of integer values, compute how many tuples (i ...

  8. 【数据结构】Hash表简介及leetcode两数之和python实现

    文章目录 Hash表简介 基本思想 建立步骤 问题 Hash表实现 Hash函数构造 冲突处理方法 leetcode两数之和python实现 题目描述 基于Hash思想的实现 Hash表简介 基本思想 ...

  9. 【LeetCode】18.四数之和

    题目描述 18. 四数之和 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 t ...

随机推荐

  1. VerificationCodeService

    package me.zhengjie.system.domain; import lombok.AllArgsConstructor; import lombok.Data; import lomb ...

  2. winfrom控件圆角

    刚好用到这个功能,看了好些例子.我就不明白,简单的一个事,一些文章里的代码写的那个长啊,还让人看么. 精简后,就其实一点,只要有paint事件的组件,都可画圆角,没有的外面套一个panel就行了. u ...

  3. transcription-coupled repair|Germ|HK|TS|Mutation|四类变异

    生命组学-可遗传变异 GC content:碱基: GC content不同的植物对应的gene length,可看作上图的转置: 由GC content看出来碱基变异程度,可以找到对应碱基改变,所以 ...

  4. Java接口和抽象类区别

    1.抽象类 [public] abstract class ClassName { abstract void fun(); } extends 包含抽象方法的类称为抽象类,但并不意味着抽象类中只能有 ...

  5. HTTP Status 400,400 (Bad Request)

    400 (Bad Request) 点击添加按钮转跳没反应,控制台没报错,然后在Chrome上检查发现报错了 百度了一下,发现http Status 400这个错误大多是因为,jsp的form表单提交 ...

  6. linux的nohup命令的用法(后台运行程序命令)

    linux的nohup命令的用法. 在应用Unix/Linux时,我们一般想让某个程序在后台运行,于是我们将常会用 & 在程序结尾来让程序自动运行.比如我们要运行mysql在后台: /usr/ ...

  7. 关联规则之FpGrowth算法

    Aprori算法利用频繁集的两个特性,过滤了很多无关的集合,效率提高不少,但是我们发现Apriori算法是一个候选消除算法,每一次消除都需要扫描一次所有数据记录,造成整个算法在面临大数据集时显得无能为 ...

  8. 对TD tree的使用体验及建议

    TDtree与QQ空间有着相似的功能,你可以在里面发表自己的感受与心情,也可以存储照片或者给喜欢的说说点赞.发表评论等,可以说这是一个将QQ空间从QQ里独立出来的软件.作为一个娱乐性的软件,它的功能还 ...

  9. 4K时代,你不能不知道的HEVC

    最近追的美剧更新啦!但手机没连wifi,看视频心疼流量:画面不清晰,老是卡机:真是令人苦恼不已.别着急,或许在HEVC大范围普及之后,这一切烦恼都将不复存在了. HEVC是什么?它是High Effi ...

  10. django Field选项中null和blank的区别

    blank只是在填写表单的时候可以为空,而在数据库上存储的是一个空字符串:null是在数据库上表现NULL,而不是一个空字符串: 需要注意的是,日期型(DateField.TimeField.Date ...