Leetcode 15. 3Sum

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

3Sum

2. Solution

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:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> result;
int length = nums.size();
for(int i = 0; i < length - 1; i++) {
if(i != 0 && nums[i] == nums[i - 1]) {
continue;
}
int target = 0 - nums[i];
int left = i + 1;
int right = length - 1;
while(left < right) {
if(left != i + 1 && nums[left] == nums[left - 1]) {
left++;
continue;
}
if(right != length - 1 && nums[right] == nums[right + 1]) {
right--;
continue;
}
int sum = nums[left] + nums[right];
if(sum == target) {
vector<int> temp;
temp.push_back(nums[i]);
temp.push_back(nums[left]);
temp.push_back(nums[right]);
result.push_back(temp);
left++;
right--;
}
else if(sum < target) {
left++;
}
else {
right--;
}
}
}
return result;
}
};

Reference

  1. https://leetcode.com/problems/3sum/description/
如果有收获,可以请我喝杯咖啡!