15.三数之和


15. 三数之和

难度中等2215

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

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

示例:

给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        int n = nums.size();
        sort(nums.begin(),nums.end());
        set<vector<int>> s;
        for(int i = 0;i<n;i++){
            int l = i+1;
            int r = n-1;
            while(l<r){
                if(nums[i]+nums[l]+nums[r]==0){
                    s.insert({nums[i],nums[l],nums[r]});
                    l++;
                    r--;
                }else if(nums[i]+nums[l]+nums[r]<0){
                    l++;
                }else{
                    r--;
                }
            }
        }
        vector<vector<int>> ret(s.begin(),s.end());
        return ret;
    }
};

先确定,第一位数字,,后面就是求TwoSum的方法,,双指针,先用set存,,最后转换成vector

文章作者: anlen123
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 anlen123 !
 上一篇
1014.最佳观光组合 1014.最佳观光组合
1014. 最佳观光组合难度中等84 给定正整数数组 A,A[i] 表示第 i 个观光景点的评分,并且两个景点 i 和 j 之间的距离为 j - i。 一对景点(i < j)组成的观光组合的得分为(A[i] + A[j] + i -
2020-06-17 anlen123
下一篇 
把python脚本当作.sh脚本使用 把python脚本当作.sh脚本使用
linux运行python脚本a.py print("2333") 需要这样 python a.py 但是现在 首先查找python的位置 which python : /usr/bin/python 编辑a.py文件 在头前加上 #!
2020-06-07 anlen123
  目录