'Find Four Elements That Sums To A Given Value : Wrong Output
I am trying to solve the question,
Given an array nums of n integers, return an array of all the unique quadruplets
[nums[a], nums[b], nums[c], nums[d]]such that:0 <= a, b, c, d < n
a, b, c, and d are distinct.
nums[a] + nums[b] + nums[c] + nums[d] == targetYou may return the answer in any order.
I think I have understood the logic that I need to implement, but my code it is not giving the desired output.
Example: Input: [-3,-2,-1,0,0,1,2,3], 0
The expected output is:
[
[-3,-2,2,3],
[-3,-1,1,3],
[-3,0,0,3],
[-3,0,1,2],
[-2,-1,0,3],
[-2,-1,1,2],
[-2,0,0,2],
[-1,0,0,1]
]
but my code outputs this:
[
[-3,-2,2,3],
[-3,-1,1,3],
[-3,0,0,3],
[-2,-1,0,3],
[-2,0,0,2],
[-1,0,0,1]
]
My C++ Code below:
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int n=nums.size();
vector<vector<int>> ans;
int low;
int high;
sort(nums.begin(),nums.end());
for(int i=0;i<n-2;i++)
{
for(int j=i+1;j<n-1;j++)
{
low=j+1;
high=n-1;
int req=target-(nums[i]+nums[j]);
while(low<high)
{
if(nums[low]+nums[high]==req)
{
ans.push_back({nums[i],nums[j],nums[low],nums[high]});
while(high>low && nums[high-1]==nums[high])
--high;
while(high>low && nums[low+1]==nums[low])
++low;
break;
}
else if(nums[low]+nums[high]>req)
{
high--;
}
else
low++;
}
while(j+1<n && nums[j]==nums[j+1])
++j;
while(i+1<n && nums[i]==nums[i+1])
++i;
}
}
return ans;
}
};
Where is the mistake?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
