简介

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

思路

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

参考链接

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;
        
    }
}
posted on 2021-05-15 20:04  HDU李少帅  阅读(36)  评论(0编辑  收藏  举报