zoukankan      html  css  js  c++  java
  • Leetcode15.3Sum三数之和

    给定一个包含 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 len = nums.size();
            sort(nums.begin(), nums.end());
            map<int, pair<int, int> > check;
            vector<vector<int> > res;
            for(int i = 0; i < len - 2; i++)
            {
                int low = i + 1;
                int high = len - 1;
                while(low < high)
                {
                    if(nums[low] + nums[high] == -nums[i])
                    {
                        res.push_back({nums[i], nums[low], nums[high]});
                        //去重
                        while(nums[low] == nums[low + 1])
                            low++;
                        low++;
                    }
                    if(nums[low] + nums[high] > -nums[i])
                    {
                        high--;
                    }
                    else
                    {
                        low++;
                    }
                }
                //去重
                while(nums[i] == nums[i + 1])
                    i++;
            }
            return res;
        }
    };
  • 相关阅读:
    文件拖拽上传
    30天自制操作系统笔记(第三天)
    PAT 1040到底有几个pat
    pat 1039 到底买不买
    pat 1038 统计同成绩学生
    pat 乙级1034
    pat 乙级1022
    pat 乙级1009
    pat 乙级1008
    pat 乙级1002
  • 原文地址:https://www.cnblogs.com/lMonster81/p/10433885.html
Copyright © 2011-2022 走看看