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]
]
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> result; //直接调用sort()函数进行排序 sort(nums.begin(),nums.end()); for(int i=0;i<nums.size();i++){ int front=i+1; int back=nums.size()-1; int target=-nums[i]; while(front<back){ int sum=nums[front]+nums[back]; if(target<sum) --back; else if(target>sum) ++front; else{ vector<int> tempRes; tempRes.push_back(nums[i]); tempRes.push_back(nums[front]); tempRes.push_back(nums[back]); result.push_back(tempRes); //寻找不重复的 while(front<back&&nums[front]==tempRes[1]) front++; while(front<back&&nums[back]==tempRes[2]) back--; } } while(i+1<nums.size()&&nums[i]==nums[i+1]) i++; } return result; } };
思路是先将所有的数据进行排序,再找出符合结果的。同时也有两个指针的使用,和昨天做的蓄水桶有共同之处。
那这样的话,2 sum问题也可以先排序再查找,但是那个问题需要返回对应的位置,这种处理方法已经将原顺序打乱了,想想还是哈希表的做法最为快捷。