zoukankan      html  css  js  c++  java
  • Leetcode: 15. 3Sum

    Description

    Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

    Example

    For example, given array S = [-1, 0, 1, 2, -1, -4],
    
    A solution set is:
    [
        [-1, 0, 1],
        [-1, -1, 2]
    ]
    

    思路

    • 找出三个数的和0的所有情况。
    • 先排序
    • 然后从前往后找 两个数的和是另外一个的负数。
    • 注意区分重复情况。即一个数若已经找过了,那下一次出现重复时应该跳过。
    • 这个题扎心了,一年前提交还是67ms,现在149ms,还是最好的一次情况。难道一年不见,大神们都成长这么快了吗

    代码

    class Solution {
    public:
        vector<vector<int>> threeSum(vector<int>& nums) {
            vector<vector<int>> res;
            
            int len = nums.size();
            if(len <= 2) return res;
            
            int index1 = 0, index2 = 0;
            int i = 0 , s, e;
            sort(nums.begin(), nums.end());
            
            for(i = 0; i < len; ++i){
                if(i > 0 && nums[i] == nums[i - 1]) continue;
                
                s = i + 1;
                e = len - 1;
                
                while(s < e){
                    if(s > i + 1 && nums[s] == nums[s - 1]){
                        s++;
                        continue;
                    } 
                    if(e < len - 1 && nums[e] == nums[e + 1]){ 
                        e--;
                        continue;
                    }
                
                    if(nums[s] + nums[e] > -nums[i]) e--;
                    else if(nums[s] + nums[e] < -nums[i]) s++;
                    else {
                        vector<int> tmp;
                        tmp.push_back(nums[i]);
                        tmp.push_back(nums[s]);
                        tmp.push_back(nums[e]);
                        res.push_back(tmp);
                        s++;
                    }
                }
            }
            
            return res;
        }
    };
    
  • 相关阅读:
    charles安装以及手机端的设置
    ON DUPLICATE KEY UPDATE 用法与说明
    亿级流量架构之网关设计思路、常见网关对比
    灰度发布系统架构设计
    Jmeter 并发测试
    springboot --- Swagger UI初识
    TortoiseGIT 一直提示输入密码的解决方法!
    MySQL 5.6 参数详解
    LVS 轮询调度详解
    MongoDB 权限
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6821219.html
Copyright © 2011-2022 走看看