18. 4Sum

Given an array nums of n integers and an integer target, are there elements abc, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

The solution set must not contain duplicate quadruplets.

Example:

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

 

AC code:

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        int len = nums.size();
        vector<vector<int>> v;
        if (len < 4) return v;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < len-3; ++i) {
            if (i > 0 && nums[i] == nums[i-1]) continue;
            if (nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target) break;
            if (nums[i] + nums[len-1] + nums[len-2] + nums[len-3] < target) continue;
            for (int j = i+1; j < len -2; ++j) {
                if (j > i+1 && nums[j] == nums[j-1]) continue;
                if (nums[i] + nums[j] + nums[j+1] + nums[j+2] > target) break;
                if (nums[i] + nums[j] + nums[len-2] + nums[len-1] < target) continue;
                int left = j + 1;
                int right = len - 1;
                while (left < right) {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum > target) {
                        right--;
                    } else if (sum < target) {
                        left++;
                    } else {
                        v.push_back(vector<int>{nums[i], nums[j], nums[left], nums[right]});
                        // don't use while statement.
                        do {
                            left++;
                        } while (left < right && nums[left] == nums[left-1]);
                        
                        do {
                            right--;
                        } while (left < right && nums[right] == nums[right+1]);
                    }
                }
            }
        }
        return v;
    }
};

Runtime: 20 ms, faster than 75.88% of C++ online submissions for 4Sum.

 

posted @ 2018-10-02 22:41  Veritas_des_Liberty  阅读(143)  评论(0编辑  收藏  举报