zoukankan      html  css  js  c++  java
  • leetcode 15 三数之和

    简介

    其实还是蛮常识的一道题, 不过, 说实话,容易超时.

    思路

    固定第一个值,然后使用左右指针, 进行滑动.

    参考链接

    https://leetcode-cn.com/problems/3sum/solution/yi-miao-jiu-neng-kan-dong-de-dong-tu-jie-unfp/

    code

    class Solution {
    public:
        vector<vector<int>> threeSum(vector<int>& nums) {
            int n = nums.size();
            sort(nums.begin(), nums.end());
            vector<vector<int> > rlt;
            if(nums.size() < 3) return rlt;
            for(int i=0; i<nums.size()-2; i++) {
                int target = 0 - nums[i];
                if( i>0 && nums[i] == nums[i-1]) {
                    continue;
                }
                int left = i +1;
                int right = nums.size() - 1;
                while(left < right) {
                    if(nums[left] + nums[right] == target) {
                        rlt.push_back({nums[i], nums[left], nums[right]});
                        while(left < right && nums[left] == nums[left + 1]) left++;
                        while(left < right && nums[right] == nums[right - 1]) right--;
                        left++;
                        right--;
                    }
                    else if(nums[left] + nums[right] > target) {
                        right--;
                    }else {
                        left++;
                    }
                }
            }
            return rlt;
        }
    };
    
        public List<List<Integer>> threeSum(int[] nums) {
            List<List<Integer>> arr = new ArrayList<List<Integer>>();
            if(nums.length < 3) return arr;
            Arrays.sort(nums);
            for(int i=0; i<nums.length; i++) {
                int l = i + 1;
                int r = nums.length - 1;
                int target = 0 - nums[i];
                if(i > 0 && nums[i] == nums[i-1]){
                    continue;
                }
                while(l < r) {
                    if(nums[l] + nums[r] == target) {
                        arr.add(new ArrayList<>(Arrays.asList(nums[i], nums[l], nums[r])));
                        while(l < r && nums[l] == nums[l+1]) l++;
                        while(l < r && nums[r] == nums[r-1]) r--;
                        l++;
                        r--;
                    }
                    else if(nums[l] + nums[r] > target) {
                        r--;
                    }else{
                        l++;
                    }
                }
            }
            return arr;
            
        }
    }
    
    Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
  • 相关阅读:
    AOP
    关于zookeeper部署的个数
    Zookeeper 简介
    Java 正则表达式
    面试记录
    面试题
    Spring Framework官方文档翻译(中英文版)
    java知识巩固
    mysql sql记录
    redis入门
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/14772402.html
Copyright © 2011-2022 走看看