3Sum LeetCode solution in C++

1
class Solution {
2
public:
3
vector<vector<int>> threeSum(vector<int> &nums) {
4
sort(nums.begin(), nums.end());
5
vector<vector<int>> ans;
6

7
for (int i = 0; i < nums.size() - 2; i++) {
8
if (i > 0 && (nums[i] == nums[i - 1])) continue;
9

10
int left_index = i + 1;
11
int right_index = nums.size() - 1;
12

13
while (left_index < right_index) {
14
int threesome = nums[i] + nums[left_index] + nums[right_index];
15
if (threesome > 0)
16
right_index--;
17
else if (threesome < 0)
18
left_index++;
19
else {
20
ans.push_back({nums[i], nums[left_index], nums[right_index]});
21

22
while (((left_index < right_index) && nums[left_index] == nums[left_index + 1]))
23
left_index++;
24
left_index++;
25
}
26
}
27
}
28

29
return ans;
30
}
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0