【C++】每日一题 15 三数之和

给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请你返回所有和为 0 且不重复的三元组。

比官方三循环快1000ms的解法,57ms,击败91.37%

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
    vector<vector<int>> result;
    int n = nums.size();
    
    sort(nums.begin(), nums.end());
    
    for (int i = 0; i < n - 2; ++i) {
        if (i == 0 || (i > 0 && nums[i] != nums[i-1])) {
            int target = -nums[i];
            int low = i + 1, high = n - 1;
            
            while (low < high) {
                if (nums[low] + nums[high] == target) {
                    result.push_back({nums[i], nums[low], nums[high]});
                    
                    while (low < high && nums[low] == nums[low+1]) low++;
                    while (low < high && nums[high] == nums[high-1]) high--;
                    
                    low++;
                    high--;
                } else if (nums[low] + nums[high] < target) {
                    low++;
                } else {
                    high--;
                }
            }
        }
    }
    
    return result;
    }
};

你可能感兴趣的:(c++,c++,算法,数据结构)