1、
Given an array S of n integers, are there elements a, b, c in S 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.
- For example, given array S = [-1, 0, 1, 2, -1, -4],
- A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
题意:给定一个数组,从中找出所有和为零的三个数,要求结果不重复
思路:从头开始遍历,对每一个数找到两个数和为它的相反数,先排序,然后从两头向中间找,注意找出所有情况和去除重复数字,时间复杂度O(n^2)。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
std::sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); ++i) {
int target = -nums[i];
int front = i + 1;
int back = nums.size() - 1;
while (front < back) {
int sum = nums[front] + nums[back];
if (sum < target)
front++;
else if (sum > target)
back--;
else {
vector<int> tmp(3, 0);
tmp[0] = nums[i];
tmp[1] = nums[front];
tmp[2] = nums[back];
res.push_back(tmp);
//跳过重复数字
while (front < back && nums[front] == tmp[1]) front++;
while (front < back && nums[back] == tmp[2]) back--;
}
}
//跳过重复数字
while (i + 1 < nums.size() && nums[i + 1] == nums[i]) i++;
}
return res;
}
};
2、Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
题意:给定S个整数和一个目标数,在S个整数中找出三个数,使他们的和距离目标数最近,结果唯一。
思路:同上,时间复杂度O(n^2);
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
if (nums.size() < 3) return 0;
int closest = nums[0] + nums[1] + nums[2];
std::sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size() - 2; ++i) {
int front = i + 1, back = nums.size()-1;
while (front < back) {
int tmp = nums[i] + nums[front] + nums[back];
if (tmp == target) return tmp;
if (abs(target - tmp) < abs(target - closest)) closest = tmp;
if (tmp > target) --back;
else ++front;
}
while (i + 1 < nums.size() && nums[i] == nums[i+1]) ++i;
}
return closest;
}
};