#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Soluation {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
// 将nums进行排序
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] > 0) return result;
// 对a去重
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1;
int right = nums.size() - 1;
while (right > left) {
if ((nums[i] + nums[left] + nums[right]) > 0) right--;
else if((nums[i] + nums[left] + nums[right]) < 0) left++;
else
{
result.push_back(vector<int> {nums[i], nums[left], nums[right]});
while (right>left && nums[left + 1] == nums[left]) left++;
while (right > left && nums[right - 1] == nums[right]) right--;
right--; left++;
}
}
}
return result;
}
};
哈希表-三数之和-双指针、vector、去重
于 2023-09-17 19:18:25 首次发布