Leetcode#18 4Sum
Published:
Link:
https://leetcode.com/problems/4sum/description/
Idea:
One more loop compare with 3sum Need to skip same target to exclude duplicated sum target.
Solution:
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> res;
if(nums.size() < 4)
return res;
sort(nums.begin(), nums.end());
for(int i=0; i<nums.size(); i++) {
if (i > 0 && nums[i] == nums[i-1])
continue;
int tmp = target - nums[i];
for(int j=i+1; j<nums.size(); j++) {
if (j > i+1 && nums[j] == nums[j-1])
continue;
int left = j+1;
int right = nums.size()-1;
int tmp2 = tmp-nums[j];
while (left < right) {
if (tmp2 == nums[left] + nums[right]) {
vector<int> ans;
ans.push_back(nums[i]);
ans.push_back(nums[j]);
ans.push_back(nums[left]);
ans.push_back(nums[right]);
res.push_back(ans);
left++;
while(left < nums.size() && nums[left] == nums[left-1]) left++;
right--;
while(right >=0 && nums[right] == nums[right+1]) right--;
} else if (tmp2 > nums[left] + nums[right]) {
left++;
} else {
right--;
}
}
}
}
return res;
}
};