Skip to content

Instantly share code, notes, and snippets.

@zhangxiaomu01
Created October 26, 2018 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangxiaomu01/ad31bbf346b00b95cf6577d1a9b651f8 to your computer and use it in GitHub Desktop.
Save zhangxiaomu01/ad31bbf346b00b95cf6577d1a9b651f8 to your computer and use it in GitHub Desktop.
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> finalResult;
int len = nums.size();
if(len <= 3)
return finalResult;
else
sort(nums.begin(), nums.end());
for(int i = 0; i< len - 3;)
{
int a = nums[i];
for(int j = i+1; j < len - 2;)
{
int b = nums[j];
for(int p = j + 1, q = len-1; p < q;)
{
int c = nums[p], d = nums[q];
int value = a + b + c + d;
if(value == target)
{
finalResult.push_back({a,b,c,d});
while(d == nums[--q] );
while(c == nums[++p]);
}
else if(value > target){
while(d == nums[--q] );
}
else{
while(c == nums[++p]);
}
}
j++;
while(nums[j-1] == nums[j]&& j<len - 2)
j++;
}
i++;
while(nums[i - 1] == nums[i] && i< len -3)
i++;
}
return finalResult;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment