leetcode-15-数组题-三数之和

题目

1.png

解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
public:

void changePosAdd(int &pos, vector<int>& nums, int n){
while((pos + 1 < n) && (nums[pos + 1] == nums[pos]))
++pos;
++pos;
}

void changePosSub(int &pos, vector<int>& nums){
while((pos - 1 > 0) && (nums[pos - 1] == nums[pos]))
--pos;
--pos;
}

vector<vector<int>> threeSum(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(), nums.end()); // 排序

vector<vector<int>> results;
int now = 0;
while(now < n-2){
int low = now + 1;
int high = n - 1;
while(low < high){
if(nums[low] + nums[high] == -nums[now]){
vector<int> res{nums[now], nums[low], nums[high]};
results.push_back(res);
changePosAdd(low, nums, n);
changePosSub(high, nums);
}else if(nums[low] + nums[high] > -nums[now]){
changePosSub(high, nums);
}else{
changePosAdd(low, nums, n);
}
}

changePosAdd(now, nums, n);
}

return results;
}
}