Skip to content

Commit 089bbde

Browse files
committed
4some👄
1 parent 2d4e5c8 commit 089bbde

File tree

2 files changed

+68
-1
lines changed

2 files changed

+68
-1
lines changed

Striver Sheet/Day-4/4Sum.cpp

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/*
2+
4Sum
3+
====
4+
5+
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:
6+
7+
0 <= a, b, c, d < n
8+
a, b, c, and d are distinct.
9+
nums[a] + nums[b] + nums[c] + nums[d] == target
10+
You may return the answer in any order.
11+
12+
Example 1:
13+
Input: nums = [1,0,-1,0,-2,2], target = 0
14+
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
15+
16+
Example 2:
17+
Input: nums = [2,2,2,2,2], target = 8
18+
Output: [[2,2,2,2]]
19+
20+
Constraints:
21+
1 <= nums.length <= 200
22+
-109 <= nums[i] <= 109
23+
-109 <= target <= 109
24+
*/
25+
26+
class Solution
27+
{
28+
public:
29+
vector<vector<int>> fourSum(vector<int> &nums, int target)
30+
{
31+
int n = nums.size();
32+
sort(nums.begin(), nums.end());
33+
vector<vector<int>> ans;
34+
35+
for (int i = 0; i < n - 3; ++i)
36+
{
37+
for (int j = i + 1; j < n - 2; ++j)
38+
{
39+
int tar = target - nums[j] - nums[i];
40+
41+
int k = j + 1, l = n - 1;
42+
while (k < l)
43+
{
44+
if (nums[k] + nums[l] == tar)
45+
{
46+
ans.push_back({nums[i], nums[j], nums[k], nums[l]});
47+
while (k < l && nums[k] == nums[k + 1])
48+
k++;
49+
while (k < l && nums[l] == nums[l - 1])
50+
l--;
51+
k++;
52+
l--;
53+
}
54+
else if (nums[k] + nums[l] < tar)
55+
k++;
56+
else
57+
l--;
58+
}
59+
while (j < n - 2 && nums[j] == nums[j + 1])
60+
j++;
61+
}
62+
while (i < n - 3 && nums[i] == nums[i + 1])
63+
i++;
64+
}
65+
return ans;
66+
}
67+
};

Striver Sheet/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
###
3333

3434
- [Two Sum](https://leetcode.com/problems/two-sum/) - [Cpp Soultion](./Day-4/Two%20Sum.cpp)
35-
- []() - [Cpp Soultion](./Day-4/.cpp)
35+
- [4Sum](https://leetcode.com/problems/4sum/) - [Cpp Soultion](./Day-4/4Sum.cpp)
3636
- []() - [Cpp Soultion](./Day-4/.cpp)
3737
- []() - [Cpp Soultion](./Day-4/.cpp)
3838
- []() - [Cpp Soultion](./Day-4/.cpp)

0 commit comments

Comments
 (0)