三數之和
描述
筆記
數據
評測
給出一個有n個整數的數組S,在S中找到三個整數a, b, c,找到所有使得a + b + c = 0的三元組。
注意事項
在三元組(a, b, c),要求a <= b <= c。
結果不能包含重複的三元組。
您在真實的面試中是否遇到過這個題? Yes
樣例
如S = {-1 0 1 2 -1 -4}, 你需要返回的三元組集合的是:
(-1, 0, 1)
(-1, -1, 2)
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) {
if(nums.size()<3) return{};//不加這句,能通過Lintode,過不了LeetCode
vector<vector<int>> v1;int i,j,p;
set<vector<int>> s;//set裏數據不重複,注意,set裏{-1,0,1}與{1,0,-1}是不同的元素,不算做重複,這裏之所以可以用set是因爲sort排序之後再插入答案,順序都是由小到大的,所以不會出現剛剛那種情況。
sort(nums.begin(),nums.end());
for( i=0;i<nums.size()-2;++i){
if(nums[i]>0) break;
int m=0-nums[i];
j=nums.size()-1;p=i+1;
while(p<j){
if(nums[p]+nums[j]==m) {s.insert({nums[i],nums[p],nums[j]});p++;j--;}//對特定的i來說,p,j不唯一,所以插入一個數後,要繼續,不能break;更不能不處理,會超時。
if(nums[p]+nums[j]<m) p++;
if(nums[p]+nums[j]>m) j--;
}
}
for(auto &c:s)
v1.push_back(c);
return v1;
}
};