这两题一个套路。
先排个序;
外循环遍历数组,选出triplet第一个数;
内循环处理该数之后的子数组,分别从头向后、从尾向前遍历,找到triplet后两个数;
3Sum Closest须另设两个变量,分别保存最接近target的和,及其与target的差距,在内循环中更新;
时间代价O(n*n)。
3Sum
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums)
{
vector< vector<int> > result;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); ++i)
{
if (nums[i] > 0)
break;
int front = i + 1;
int back = nums.size() - 1;
int target = -nums[i];
while (front < back)
{
int sum = nums[front] + nums[back];
if (sum < target) ++front;
if (sum > target) --back;
if (sum == target)
{
vector<int> triplet(3, 0);
triplet[0] = nums[i];
triplet[1] = nums[front];
triplet[2] = nums[back];
result.push_back(triplet);
while (nums[front] == triplet[1] && front < back) ++front;
while (nums[back] == triplet[2] && front < back) --back;
}
}
while (nums[i] == nums[i + 1] && i < nums.size() - 1) ++i;
}
return result;
}
};
3Sum Closest
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target)
{
int result = 0;
if (nums.size() < 3)
return 0;
sort(nums.begin(), nums.end());
int closetDist = INT_MAX;
for (int i = 0; i < nums.size(); ++i)
{
int left = i + 1;
int right = nums.size() - 1;
int sum = 0;
while (left < right)
{
sum = nums[i] + nums[left] + nums[right];
if (sum < target) ++left;
if (sum > target) --right;
if (sum == target) return sum;
if (abs(sum - target) < closetDist)
{
result = sum;
closetDist = abs(sum - target);
}
}
}
return result;
}
};
Reference:
https://leetcode.com/discuss/23595/share-my-solution-around-50ms-with-explanation-and-comments