LeetCode Week 11
阿新 • • 發佈:2018-12-08
18. 4Sum
Given an array nums of n integers and an integer target, are there elements a, b, c, 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]
]
solutions:
本題意是要求給定n個整數的陣列num和一個整數目標,那麼num中是否有元素a、b、c和d,使得a+b+c+d=目標值?在給出目標和的陣列中找到所有唯一的四胞胎。
先將陣列排序,第一第二個元素迴圈遍歷,第三第四可以比較sum和target的大小,選擇向那個方向進行遍歷。
class Solution { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { sort(nums.begin(), nums.end()); vector<vector<int>> res; if(nums.size() < 4) return res; for(int first = 0; first < nums.size() - 3; first++) { if(first != 0 && nums[first] == nums[first - 1]) continue; for(int second = first + 1; second < nums.size() - 2; second++) { if(second != first + 1 && nums[second] == nums[second - 1]) continue; int left = second + 1; int right = nums.size() - 1; while(left < right) { int sum = nums[first] + nums[second] + nums[left] + nums[right]; if(sum < target) left++; else if(sum > target) right--; else { res.push_back({nums[first], nums[second], nums[left], nums[right]}); left++; while(left < right && nums[left] == nums[left - 1]) { left++; } } } } } return res; } };