File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ vector<vector<int >> fourSum (vector<int >& nums, int target) {
4
+ vector<vector<int >> result;
5
+ int n = nums.size ();
6
+ if (n < 4 ) return result;
7
+
8
+ sort (nums.begin (), nums.end ());
9
+
10
+ for (int i = 0 ; i < n - 3 ; i++) {
11
+ if (i > 0 && nums[i] == nums[i - 1 ]) continue ; // skip duplicates for i
12
+
13
+ for (int j = i + 1 ; j < n - 2 ; j++) {
14
+ if (j > i + 1 && nums[j] == nums[j - 1 ]) continue ; // skip duplicates for j
15
+
16
+ int left = j + 1 ;
17
+ int right = n - 1 ;
18
+
19
+ while (left < right) {
20
+ long long sum = (long long )nums[i] + nums[j] + nums[left] + nums[right];
21
+
22
+ if (sum == target) {
23
+ result.push_back ({nums[i], nums[j], nums[left], nums[right]});
24
+
25
+ // skip duplicates for left
26
+ while (left < right && nums[left] == nums[left + 1 ]) left++;
27
+ // skip duplicates for right
28
+ while (left < right && nums[right] == nums[right - 1 ]) right--;
29
+
30
+ left++;
31
+ right--;
32
+ }
33
+ else if (sum < target) left++;
34
+ else right--;
35
+ }
36
+ }
37
+ }
38
+ return result;
39
+ }
40
+ };
You can’t perform that action at this time.
0 commit comments