首页 > 其他分享 >【LeetCode】三数之和

【LeetCode】三数之和

时间:2023-02-16 18:44:06浏览次数:40  
标签:nums ++ 三数 三元组 vector res LeetCode

三数之和

题目描述

给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请

你返回所有和为 0 且不重复的三元组。

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

 

 

示例 1:

输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
解释:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0 。
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0 。
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0 。
不同的三元组是 [-1,0,1] 和 [-1,-1,2] 。
注意,输出的顺序和三元组的顺序并不重要。
示例 2:

输入:nums = [0,1,1]
输出:[]
解释:唯一可能的三元组和不为 0 。
示例 3:

输入:nums = [0,0,0]
输出:[[0,0,0]]
解释:唯一可能的三元组和为 0 。
 

提示:

3 <= nums.length <= 3000
-105 <= nums[i] <= 105

思路

对数组排序,先用一个下标遍历数组,然后数组的后半部分用双指针,去查找符合条件的,并且要注意边界条件和一些优化方法

vector<vector<int>> threeSum(vector<int>& nums) {
    vector<vector<int>> res;
    int n = nums.size();
    if (n < 3) return res;
    sort(nums.begin(), nums.end());
    for (int i = 0; i < n; i++) {
        if (nums[i] > 0) break; // 由于nums[i] 是三个数中最小的,如果nums[i]>0,则三个数加起来一定不会等于0,因此要跳出循环
        while (i < n && i > 0 && nums[i] == nums[i - 1]) i++; // nums[i] 与 nums[i-1]重复,故向后移动,去重
        int l = i + 1, r = n - 1; // 双指针在数组的后半部分进行查找
        while (l < r) {
            int sum = nums[i] + nums[l] + nums[r];
            if (sum == 0) { // 找到了一组符合条件的答案,加入res中
                vector<int> tmp{nums[i], nums[l], nums[r]};
                res.push_back(tmp);
                while (l < r && nums[l] == nums[l + 1]) l++; // 去重
                while (l < r && nums[r] == nums[r - 1]) r--; // 去重
                l ++;
                r --;
            }
            else if(sum < 0) l++; // 三数之小于0,说明nums[l]小了,则l向后移动
            else if(sum > 0) r--; // 三数之大于0,说明nums[r]大了,则r向前移动
        }
    }
    return res;
}

参考了别人的题解

标签:nums,++,三数,三元组,vector,res,LeetCode
From: https://www.cnblogs.com/basilicata/p/17127818.html

相关文章

  • 【LeetCode】15. 三数之和
    classSolution{public:vector<vector<int>>threeSum(vector<int>&nums){vector<vector<int>>result;sort(nums.begin(),nums.end());......
  • 代码随想录算法训练营day22 | leetcode 235. 二叉搜索树的最近公共祖先 ● 701.二叉
    LeetCode235.二叉搜索树的最近公共祖先分析1.0 二叉搜索树根节点元素值大小介于子树之间,所以只要找到第一个介于他俩之间的节点就行classSolution{publicTre......
  • [LeetCode] 2341. Maximum Number of Pairs in Array
    Youaregivena 0-indexed integerarray nums.Inoneoperation,youmaydothefollowing:Choose two integersin nums thatare equal.Removebothinte......
  • leetcode 11. 盛最多水的容器 js实现
    给定一个长度为n的整数数组 height 。有 n 条垂线,第i条线的两个端点是 (i,0) 和 (i,height[i]) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容......
  • Leetcode736 Lisp语法解析
      解法主要有两项工作:1、处理作用域(栈或递归);2、顺序处理逻辑:(1)根据分隔符将语句拆解为token;(2)根据关键字的运算逻辑定义状态,设计自动机;(3)从左至右逐个解析......
  • 【算法训练营day45】LeetCode70. 爬楼梯(进阶) LeetCode322. 零钱兑换 LeetCode279. 完
    LeetCode70.爬楼梯(进阶)题目链接:70.爬楼梯(进阶)独上高楼,望尽天涯路可以把爬楼梯看成是一个排序问题加完全背包。classSolution{public:intclimbStairs(intn)......
  • leetcode-1365-easy
    HowManyNumbersAreSmallerThantheCurrentNumberGiventhearraynums,foreachnums[i]findouthowmanynumbersinthearrayaresmallerthanit.Thatis......
  • leetcode-1374-easy
    GenerateaStringWithCharactersThatHaveOddCountsGivenanintegern,returnastringwithncharacterssuchthateachcharacterinsuchstringoccursan......
  • leetcode-1051-easy
    HeightCheckerAschoolistryingtotakeanannualphotoofallthestudents.Thestudentsareaskedtostandinasinglefilelineinnon-decreasingorderby......
  • leetcode-1323-easy
    Maximum69NumberYouaregivenapositiveintegernumconsistingonlyofdigits6and9.Returnthemaximumnumberyoucangetbychangingatmostonedigit......