当前位置:网站首页>【7.5】15. Sum of three numbers

【7.5】15. Sum of three numbers

2022-07-07 23:34:00 howtoloveyou

Yes vector Line up quickly from small to large :sort(nums.begin(), nums.end());
Yes vector Line up quickly from big to small :sort(nums.begin(), nums.end(), greater<int>());

#define MAX_INF 1e7
class Solution {
    
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
    
        sort(nums.begin(), nums.end());
        vector<vector<int>> ret;
        vector<int> ans;
        vector<int> pre_ans;
        int a = -MAX_INF, b, c;
        int b_ptr, c_ptr;
        if(nums.size() < 3) return ret;

        for(int i = 0; i < nums.size() - 2; i++) {
    
            if(a != nums[i]) {
    
            a = nums[i];
            b = nums[i + 1];
            b_ptr = i + 1;
            c = nums[nums.size() - 1];
            c_ptr = nums.size() - 1;
            while(b_ptr < c_ptr) {
    
                //printf("a: %d, b: %d, c: %d\n", a, b, c);
                if((a + b + c) < 0) {
    
                    b_ptr++;
                    b = nums[b_ptr];
                } else if((a + b + c) > 0) {
    
                    c_ptr--;
                    c = nums[c_ptr];
                } else {
    
                    ans.push_back(a);
                    ans.push_back(b);
                    ans.push_back(c);
                    if(pre_ans.size() == 0 || pre_ans != ans) {
    
                        pre_ans = ans;
                        ret.push_back(ans);
                        ans.pop_back();
                        ans.pop_back();
                        ans.pop_back();
                    } else if(pre_ans == ans) {
    
                        ans.pop_back();
                        ans.pop_back();
                        ans.pop_back();
                    }
                    b_ptr++;
                    b = nums[b_ptr];
                }
            }}
        }
        return ret;
    }
};
原网站

版权声明
本文为[howtoloveyou]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207072057182342.html