Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- vector<vector<int> > fourSum(vector<int> &arr, int k) {
- // Your code goes here
- sort(arr.begin(),arr.end());
- vector<vector<int>>ans;
- for(int i=0 ; i<arr.size() ; i++)
- {
- if(i>0 && arr[i]==arr[i-1])
- {
- continue;
- }
- for(int j=arr.size()-1 ; j>=i+3 ; j--)
- {
- if(j<arr.size()-1 && arr[j]==arr[j+1])
- {
- continue;
- }
- int low =i+1;
- int high=j-1;
- while(low<high)
- {
- int sum=arr[i]+arr[j]+arr[low]+arr[high];
- if(sum==k)
- {
- ans.push_back({arr[i],arr[low],arr[high],arr[j]});
- while(arr[low]==arr[low+1])
- {
- low++;
- }
- low++;
- while(arr[high]==arr[high-1])
- {
- high--;
- }
- high--;
- }
- else if(sum<k)
- {
- while(arr[low]==arr[low+1])
- {
- low++;
- }
- low++;
- }
- else{
- while(arr[high]==arr[high-1])
- {
- high--;
- }
- high--;
- }
- }
- }
- }
- sort(ans.begin(),ans.end());
- return ans;
- }
- // https://practice.geeksforgeeks.org/problems/find-all-four-sum-numbers1732/
Advertisement
Add Comment
Please, Sign In to add comment