#58 4Sum

題目描述:

Given an array S of n integers, are there elements abc, andd in S such that a + b + c + d = target?

Find all unique quadruplets in the array which gives the sum of target.

 Notice

Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.

Example

Given array S = {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)
題目思路:

這題和3 sum差不多,只是多了一個未知數。那加一層循環就可以用two pointers的算法了。

Mycode(AC = 291ms):

class Solution {
public:
    /**
     * @param numbers: Give an array numbersbers of n integer
     * @param target: you need to find four elements that's sum of target
     * @return: Find all unique quadruplets in the array which gives the sum of 
     *          zero.
     */
    vector<vector<int> > fourSum(vector<int> nums, int target) {
        // write your code here
        vector<vector<int>> ans;
        if (nums.size() <= 3) return ans;
        
        sort(nums.begin(), nums.end());
        
        set<vector<int>> visited;
        for (int i = 3; i < nums.size(); i++) {
            for (int j = 2; j < i; j++) {
                
                // use two pointers method to search
                // rest of 2 numbers
                int l = 0, r = j - 1;
                while (l < r) {
                    int sum = nums[l] + nums[r] + nums[j] + nums[i];
                    if (sum == target) {
                        if (visited.find({nums[l], nums[r], nums[j], nums[i]}) == visited.end()) {
                            ans.push_back({nums[l], nums[r], nums[j], nums[i]});
                            visited.insert({nums[l], nums[r], nums[j], nums[i]});
                        }
                        
                        l++;
                        r--;
                    }
                    else if (sum < target) {
                        l++;
                    }
                    else {
                        r--;
                    }
                }
            }
        }
        
        return ans;
    }
};


發佈了221 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章