leetcode专题训练 18. 4Sum

排序、固定两个数然后再用之前说过的双指针方法求解。

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        sort (nums.begin(), nums.end());
        int l = nums.size();
        vector<vector<int>> result;
        result.clear();
        for (int i = 0; i < l - 3; i++) {
            if (i != 0 && nums[i] == nums[i - 1]) continue;
            for (int m = i + 1; m < l - 2; m++) {
                if (m != i + 1 && nums[m] == nums[m - 1]) continue;
                int tmp_sum = nums[i] + nums[m];
                int tmp_target = target - tmp_sum;
                int j = m + 1;
                int k = l - 1;
                while (j < k) {
                    int tmp = nums[j] + nums[k];
                    if (tmp == tmp_target) {
                        vector<int> tmp_result;
                        tmp_result.push_back(nums[i]);
                        tmp_result.push_back(nums[m]);
                        tmp_result.push_back(nums[j]);
                        tmp_result.push_back(nums[k]);
                        result.push_back(tmp_result);
                        while (j < k && nums[j + 1] == nums[j]) j++;
                        while (j < k && k != l - 1 && nums[k - 1] == nums[k]) k--;
                        j++;
                        k--;
                    } else if (tmp < tmp_target) {
                        while (j < k && nums[j + 1] == nums[j]) j++;
                        j++;
                    } else if (tmp > tmp_target) {
                        while (j < k && k != l - 1 && nums[k - 1] == nums[k]) k--;
                        k--;
                    }
                }
            }
        }
        return result;
    }
};

你可能感兴趣的:(leetcode专题训练 18. 4Sum)