0
点赞
收藏
分享

微信扫一扫

LeetCode-15. 3Sum

boom莎卡拉卡 2022-08-10 阅读 56


Given an array ​​nums​​ of n integers, are there elements abc in ​​nums​​ such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

题解:

去重参考了讨论区,只想到了set暴力去重,132ms。

class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int n = nums.size();
vector<vector<int>> ans;
sort(nums.begin(), nums.end());
for (int i = 0; i < n - 2; i++) {
int j = i + 1, k = n - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum == 0) {
ans.push_back({nums[i], nums[j], nums[k]});
j++;
k--;
while (nums[j] == ans.back()[1]) {
j++;
}
while (nums[k] == ans.back()[2]) {
k--;
}
}
else if (sum > 0) {
k--;
}
else {
j++;
}
}
while (nums[i] == nums[i + 1]) {
i++;
}
}
return ans;
}
};

 

举报

相关推荐

0 条评论