zoukankan      html  css  js  c++  java
  • 15. 三数之和. 双指针法⭐

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

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

    示例:

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

    满足要求的三元组集合为:
    [
    [-1, 0, 1],
    [-1, -1, 2]
    ]

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/3sum

    class Solution {
    public:
        vector<vector<int>> threeSum(vector<int>& nums) {
            int n = nums.size();
    
            sort(nums.begin(),nums.end());
    
            vector <vector<int>> ans;
    
            for (int i = 0; i < n; i++){
                //要求与上一次枚举的数不同
                if (i > 0 && nums[i] == nums[i - 1]){
                    continue;
                }
                //k对应指针指向数组最右端
                int k = n - 1;
                int target = -nums[i];
                //转化为twosum,使用双指针法
                //枚举j
                for (int j = i + 1; j < n; j++){
                    //要求与上一次枚举的数不同
                    if (j > i + 1 && nums[j] == nums[j - 1]){
                        continue;
                    }
                    //保证j必定在k的左侧
                    while (j < k && nums[j] + nums[k] > target){
                        k--;
                    }
                    //条件判断
                    if (j == k) break;
                    //输出结果
                    if (nums[j] + nums[k] == target){
                        ans.push_back({nums[i],nums[j],nums[k]});
                    }
                }
            }
    
            return ans;
        }
    };
    
  • 相关阅读:
    Python中 sys.argv[]的用法简明解释
    python多线程
    python 多进程
    shell----bash
    linux crontab
    Elastic search 概述
    Elastic search 入门
    Elastic search CURL命令
    Elastic search 基本使用
    Elastic search 字段折叠 collaose
  • 原文地址:https://www.cnblogs.com/xgbt/p/13111033.html
Copyright © 2011-2022 走看看