题目描述
给你一个包含n个整数的数组nums,判断nums中是否存在三个元素a,b, c,使得a+b+c=0 ?请你找出所有和为0且不重复的三元组。
举例:
e.g.1 输入:nums={-1, 0, 1, 2, -1, 4}
输出: [{-1,-1,2}, {-1,0,1}]
e.g.2 输入:nums =[] 输出: []
e.g.3 输入: nums[0] 输出: []
解题方法: 排序 + 双指针
代码
#include <iostream>
#include <algorithm> //sort
#include <functional>//lambda
#include <vector>
std::vector<std::vector<int> > three_sum(std::vector<int> nums) {
int n = nums.size();
if (n < 3) {
return {};
}
// 先升序排列数组
std::sort(nums.begin(), nums.end(),[](int a, int b) {return a < b;});
std::vector<std::vector<int> > result;
int first = 0;
for (first = 0; first < n; first++) {
if (nums[first] > 0) { //第一个数字大于0,三数之和比如大于0
return result;
}
if (first > 0 && nums[first] == nums[first - 1]) { //第一个数不重复
continue;
}
int second = first + 1; //第二个数必须在第一个数之后
int third = n - 1;
while (second < third) { // 第三个数必须在第二个数之后
if (second > first + 1) { // 同一个first下,第二个数不能重复
while (second < third && nums[second] == nums[second -1]) {
second++;
}
}
if (third < n - 1) { // 第三个数必须在第二个数之后,且不重复
while (second < third && nums[third] == nums[third + 1]) {
third--;
}
}
int sum = nums[first] + nums[second] + nums[third];
if (sum == 0) {
result.push_back({nums[first], nums[second], nums[third]});
second++;
third--;
} else if (sum < 0) {
second++;
} else {
third--;
}
}
}
return result;
}
void print(const std::vector<int>& input,
const std::vector<std::vector<int> >& output) {
std::cout << "input:";
for (auto value : input) {
std::cout << value << " ";
}
std::cout << std::endl;
std::cout << "output:" << std::endl;
for (auto& vec : output) {
for (auto value : vec) {
std::cout << value << " ";
}
std::cout << std::endl;
}
}
int main() {
// case1 : [-1,0,1,2,-1,-4]
std::vector<int> nums = {-1, 0, 1, 2, -1, -4};
auto result = three_sum(nums);
print(nums, result);
// case2 :[]
nums = {};
result = three_sum(nums);
print(nums, result);
// case3 : [0]
nums = {0};
result = three_sum(nums);
print(nums, result);
}
代码运行结果如下:
input:-1 0 1 2 -1 -4
output:
-1 -1 2
-1 0 1
input:
output:
input:0
output: