LeetCode 3Sum

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。 > 例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], > > 满足要求的三元组集合为: > [ > [-1, 0, 1], > [-1, -1, 2] > ]

解答:

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
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
int len = nums.size();
sort(nums.begin(), nums.end());

if (nums.empty() || nums[0] > 0 || nums[len -1] < 0)
return {};

for (int i = 0; i < len - 2; i++) {
if (nums[i] > 0) break;
if (i > 0 && nums[i] == nums[i-1]) continue;
int j = i + 1, k = len - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum == 0) {
res.push_back(vector<int>{nums[i], nums[j], nums[k]});
while (j < k && nums[j+1] == nums[j]) ++j;
while (j < k && nums[k-1] == nums[k]) --k;
++j; --k;
} else if (sum > 0)
--k;
else
++j;
}
}
return res;
}
};

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×