File tree 1 file changed +40
-0
lines changed
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
+ int len = nums.size ();
5
+ vector<vector<int >> ans;
6
+ if (len < 4 )return ans;
7
+ sort (nums.begin (),nums.end ());
8
+
9
+ int left;
10
+ int right;
11
+ int sum;
12
+ for (int i = 0 ;i<len;i++){
13
+ if (i> 0 && nums[i] == nums[i-1 ])continue ;
14
+ for (int j = i + 1 ;j<len;j++){
15
+ if (j > i+1 && nums[j] == nums[j-1 ])continue ;
16
+
17
+ left = j+1 ;
18
+ right = len - 1 ;
19
+
20
+ while (left < right){
21
+
22
+ sum = nums[i] + nums[j] + nums[left] + nums[right];
23
+
24
+ if (sum == target){
25
+ vector<int > tmp{nums[i],nums[j],nums[left],nums[right]};
26
+ ans.push_back (tmp);
27
+
28
+ while (left < right && nums[left] == nums[left+1 ])left++;
29
+ while (left < right && nums[right] == nums[right-1 ])right--;
30
+ left++;
31
+ right--;
32
+ }
33
+ else if (sum < target)left++;
34
+ else if (sum > target)right--;
35
+ }
36
+ }
37
+ }
38
+ return ans;
39
+ }
40
+ };
You can’t perform that action at this time.
0 commit comments