问题描述:
给定一个整形数组nums,一个整形目标值target,从中找到3个整数的组合,使其和等于target。找到所有且不相同的组合。
本题target为0,不为0时只需把0替换为target即可。
以下是C++代码,Accepted。本人菜鸟一个,欢迎大家指正。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ret;
if (nums.size() < 3) return ret;
sort(nums.begin(), nums.end(), less<int>());
int preValue = nums[0];
vector<int> triple(3, 0);
vector<int>::size_type numsCount = nums.size();
for (vector<int>::size_type first = 0; first < numsCount - 2; first++) {
if (first != 0 && nums[first] == preValue) {
continue;
}
vector<int>::size_type second = first + 1;
vector<int>::size_type third = numsCount - 1;
triple[0] = nums[first];
while (second < third) {
int sum = nums[first] + nums[second] + nums[third];
if (sum < 0) {
second++;
}
else if (sum > 0) {
third--;
}
else {
triple[1] = nums[second];
triple[2] = nums[third];
if (ret.empty() || triple != *(ret.end() - 1)) {
ret.push_back(triple);
}
second++;
third--;
}
}
preValue = nums[first];
}
return ret;
}
};