审时度势 | 先记下

#include <stdio.h>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        //如果数组长度小于2直接返回空
        vector<vector <int>> ans;
        int  n = nums.size();
        if(n <= 2)
            return ans;
        sort(nums.begin(), nums.end());
        for(int i = 0; i < n; ++i){
            if(nums[i] > 0)
                return ans;
            if(nums[i] == nums[i - 1] && i >= 1)
                continue;                   //去重
            int left = i + 1;
            int right = n - 1;
            while(left < right){
                //三个数的和小于0
                if((nums[i] + nums[left] + nums[right]) < 0)
                    left++;
                //三个数的和大于0
                if((nums[i] + nums[left] + nums[right]) > 0)
                    right--;
                if((nums[i] + nums[left] + nums[right]) == 0){
                    ans.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--;
                }
            }
        }
        return ans;

    }
};

int main(){

    vector<int> t1 = {-1,0,1,2,-1,-4};
    //vector<int> t1 = {0,1,1};
    Solution a1;
    vector<vector<int>> t2 = a1.threeSum(t1);
    for(auto x : t2){
        cout<<x[0]<<" "<<x[1]<<" "<<x[2]<<endl;
    }
    return 0;
}

/*
Line 1034: Char 34: runtime error: addition of unsigned offset to 0x603000000070 overflowed to 0x60300000006c (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34
自己去编译了,可以跑通,但是leecode就是过不去,说啥的都有,数组下标越界到-1了
所以说错了啊!
-4 2 2
-1 -1 2
-1 0 1
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值