Featured image of post 4Sum

4Sum

18. 4Sum

分析

与三数之和一样,只是这里要枚举两个位置 i 和 j。

C++代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
    typedef long long LL;

    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> res;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size(); i ++ ) {
            if (i && nums[i] == nums[i - 1]) continue;
            for (int j = i + 1; j < nums.size(); j ++ ) {
                if (j > i + 1 && nums[j] == nums[j - 1]) continue;
                for (int k = j + 1, l = nums.size() - 1; k < l; k ++ ) {
                    if (k > j + 1 && nums[k] == nums[k - 1]) continue;
                    while (l - 1 > k && (LL)nums[i] + nums[j] + nums[k] + nums[l - 1] >= target) l -- ;
                    if ((LL)nums[i] + nums[j] + nums[k] + nums[l] == (LL)target) {
                        res.push_back({nums[i], nums[j], nums[k], nums[l]});
		            }
                }
            }
        }
        return res;
    }
};
Built with Hugo
Theme Stack designed by Jimmy