题解 | #四数之和#

四数之和

https://www.nowcoder.com/practice/d5b74806fa104518903884e182f47e35

class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param nums int整型vector
     * @param target int整型
     * @return int整型vector<vector<>>
     */
    vector<vector<int> > fournumber(vector<int>& nums, int target) {
        // write code here
        std::vector<std::vector<int>> result;
        if (nums.size() < 4) return result;

        std::sort(nums.begin(), nums.end());

        for (int i = 0; i < nums.size() - 3; ++i) {
            if (i > 0 &&
                    nums[i] == nums[i - 1]) continue;  // Skip duplicates for the first number

            for (int j = i + 1; j < nums.size() - 2; ++j) {
                if (j > i + 1 &&
                        nums[j] == nums[j - 1]) continue;  // Skip duplicates for the second number

                int left = j + 1;
                int right = nums.size() - 1;

                while (left < right) {
                    long long sum = (long long)nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum == target) {
                        result.push_back({nums[i], nums[j], nums[left], nums[right]});
                        while (left < right &&
                                nums[left] == nums[left + 1]) ++left;  // Skip duplicates for the third number
                        while (left < right &&
                                nums[right] == nums[right - 1]) --right;  // Skip duplicates for the fourth number
                        ++left;
                        --right;
                    } else if (sum < target) {
                        ++left;
                    } else {
                        --right;
                    }
                }
            }
        }

        return result;
    }
};

全部评论

相关推荐

牛客279957775号:铁暗恋
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务