• 15. 三数之和(双指针)


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

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

    示例 1:

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

    输入:nums = []
    输出:[]
    示例 3:

    输入:nums = [0]
    输出:[]
     

    提示:

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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/3sum
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    class Solution {
    public:
        vector<vector<int>> threeSum(vector<int>& nums) {
            int len = nums.size();
            vector<vector<int>> res;
            if(len < 3)
            {
                return res;
            }
            sort(nums.begin(), nums.end());
            const int target = 0;
            for(int first = 0; first< len; first++)
            {
                if(first > 0 && nums[first] == nums[first-1])
                {
                    continue;
                }
                int third = len-1;
                for(int second = first +1; second < third; second++)
                {
                    if(second > first+1 && nums[second] == nums[second - 1])
                    {
                        continue;
                    }
                    while(third > second && nums[first] + nums[second] + nums[third] > target)
                    {
                        third--;
                    }
                    if(second < third && (nums[first] + nums[second] + nums[third]  == 0))
                    {
                        vector<int> tmp ;
                        tmp.push_back(nums[first]);
                        tmp.push_back(nums[second]);
                        tmp.push_back(nums[third]);
                        res.push_back(tmp);
                    }
    
                }
            }
        return res;
        }
    };
    

      

  • 相关阅读:
    C# richTextBox封装的一个打印的类
    RichtextBox打印
    RichTextBox选中文本时往自己的其他的位置实现拖拽
    C# 保存和读取TreeView展开的状态
    RichtextBox去除闪烁光标
    自己重启自己
    记录一次shell里局部变量的问题
    Redis配置总结
    Nginx原理和配置总结
    CentOS7+Nginx+多个Tomcat配置
  • 原文地址:https://www.cnblogs.com/qiaozhoulin/p/14940569.html
Copyright © 2020-2023  润新知