15. 三数之和

亦凉 2023-02-08 12:49 213阅读 0赞

链接:https://leetcode-cn.com/problems/3sum

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。

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

示例 1:

  1. 输入:nums = [-1,0,1,2,-1,-4]
  2. 输出:[[-1,-1,2],[-1,0,1]]

示例 2:

  1. 输入:nums = []
  2. 输出:[]

示例 3:

  1. 输入:nums = [0]
  2. 输出:[]

题目分析

  1. 这道题的暴力解法 实在是太糙了,O(n^3)的时间复杂度,谁能忍
  2. 怎么优化呢?很简单,a + b + c = 0,转换为 b + c = -a。固定一个数,然后寻找两数之和等于 -a 。
  3. 熟悉的味道回来了,找两数之和的过程,不就是 twoSum 吗。没错,差不多。但稍有区别:
    第一点:twoSum 要求返回元素下标,因此解题时,不能改变数组位置,排序等操作都会改变下标,只好老老实实用 HashMap 记录访问过的元素。
    第二点:threeSum 要求返回三元组 a b c ,它是元素的值。因此条件更为宽松,这样我们就想到,除了套用 HashMap 的方法之外,可以先对数组按照小到大排序,排序之后使用 双指针法 优化 ,有利于优化空间复杂度。

代码实现

  1. class Solution {
  2. public List<List<Integer>> threeSum(int[] nums) {
  3. int length = nums.length;
  4. List<List<Integer>> res = new ArrayList<>();
  5. Arrays.sort(nums); // O(nlogn)
  6. for (int i = 0 ; i < length; i++) {
  7. if (i > 0 && nums[i] == nums[i-1]) {
  8. continue; // 去重
  9. }
  10. List<List<Integer>> twoSumRes = twoSum(nums, i + 1, -nums[i]);
  11. for (List<Integer> ans : twoSumRes) {
  12. res.add(Arrays.asList(nums[i], ans.get(0), ans.get(1)));
  13. }
  14. }
  15. return res;
  16. }
  17. public List<List<Integer>> twoSum(int[] nums, int start, int target) {
  18. List<List<Integer>> res = new ArrayList<>();
  19. int j = nums.length - 1;
  20. int i = start;
  21. while (i < j) {
  22. if (i > start && nums[i] == nums[i-1]) {
  23. i++;
  24. continue; // 去重
  25. }
  26. if (nums[i] + nums[j] == target) {
  27. List<Integer> tmp = new ArrayList<>();
  28. tmp.add(nums[i]);
  29. tmp.add(nums[j]);
  30. res.add(tmp);
  31. i++;
  32. } else if (nums[i] + nums[j] < target) {
  33. i++; // nums从小到大排序,小于 target时,左边指针右移,才有机会
  34. } else {
  35. j--;
  36. }
  37. }
  38. return res;
  39. }
  40. }

时间复杂度:O(n^2)
空间复杂度:O(n),用了新的空间,装载排序后的数组
在这里插入图片描述

本篇完

发表评论

表情:
评论列表 (有 0 条评论,213人围观)

还没有评论,来说两句吧...

相关阅读

    相关 15.之和

    [题目][Link 1] 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足

    相关 15. 之和

    链接:https://leetcode-cn.com/problems/3sum 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,

    相关 15.之和

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