做了2sum, 紧接着又做了3sum,发现直接套用hashmap好像有点问题~
1. Description
- Given an array nums of n integers, are there elements a, b, c in nums 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.
Example:
- Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
- [
[-1, 0, 1],
[-1, -1, 2]
]
2. 使用HashMap
思路, 直接套用hashmap, 利用中间变量, 将3sum问题转换为2sum问题。一个问题就是这个会出现很多重复的元素,所以我们在内部使用vector的erase和unique结合的方式删除重复的元素就好啦。
参考文章:
CPP code:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
unordered_map<int, int>index;
vector<vector<int>> result;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); ++i){
index[nums[i]] = i;
}
for(int i = 0;i < nums.size(); ++i){
int target = nums[i];
for (int j = i+1; j < nums.size(); ++j){
int left = - target - nums[j];
vector<int> temp = {target, nums[j], left};
sort(temp.begin(), temp.end());
if (index.count(left) && j != index[left] && i!= index[left]){
result.push_back(temp);
}
}
}
sort(result.begin(), result.end());
result.erase(unique(result.begin(), result.end()), result.end());
return result;
}
};
但是:
程序是可以正常的运行,但是竟然超时了~难受。
3. 使用 Two pointers?
上面的算法超时的主要原因是他是先穷举所有可能的情况,然后在进行排序,然后在删除重复的元素。所以我们转变思路,能不能直接跳过这个重复的情况,这样我们就可以大大减少重复的时间。
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++){
int target = - nums[i];
int first = i + 1;
int end = nums.size() - 1;
while(first < end){
int sum = nums[first] + nums[end];
if (sum < target)
first++;
else if (sum > target)
end--;
else{
vector<int>sub_result(3, 0);
sub_result[0] = nums[i];
sub_result[1] = nums[first];
sub_result[2] = nums[end];
result.push_back(sub_result);
// Processing duplicates of Number 2
while((first < end)&& (nums[first] == sub_result[1]))
first++;
// Processing duplicates of Number 3
while((first < end)&& (nums[end]== sub_result[2]))
end--;
}
}
// Processing duplicates of Number 1
while((i+1 < nums.size()) && (nums[i+1] == nums[i]))
i++;
}
return result;
}
};