C++
把3个数求和,转变为2个数求和
1. 把数组排序
2. 注意过滤重复值
3. 从前到后遍历,游标i
4. 从后边数中找start + end = -arr[i]的2 sum
5. start + end < -arr[i], start++
6. start + end > -arr[i], end--
7. start + end = -arr[i], insert <i, start, end> into result vecotr
class Solution {
public:
/**
* @param numbers : Give an array numbers of n integer
* @return : Find all unique triplets in the array which gives the sum of zero.
*/
vector<vector<int> > threeSum(vector<int> &nums) {
// write your code here
vector<vector<int> > result; sort(nums.begin(), nums.end());
for (int i = ; i < nums.size(); i++) {
if (i > && nums[i] == nums[i - ]) {
continue;
}
// two sum;
int start = i + , end = nums.size() - ;
int target = -nums[i];
while (start < end) {
if (start > i + && nums[start - ] == nums[start]) {
start++;
continue;
}
if (nums[start] + nums[end] < target) {
start++;
} else if (nums[start] + nums[end] > target) {
end--;
} else {
vector<int> triple;
triple.push_back(nums[i]);
triple.push_back(nums[start]);
triple.push_back(nums[end]);
result.push_back(triple);
start++;
}
}
} return result;
}
};