題目:
Given an array S of n integers, are there elements a, b, c in S 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.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
求解:
class Solution {
public:
bool midFind(vector<int>& v , int s, int e , int data){
int m = -1 ;;
while( s <= e){
m = s + (( e - s ) >> 1 );
if(v[m] == data){
return true;
}
else if(data < v[m]){
e = m - 1 ;
}
else{
s = m + 1 ;
}
}
return false;
}
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
sort(nums.begin(),nums.end());
int len = nums.size();
for(int i = 0 ; i < len ; i++){
if(i != 0 && nums[i] == nums[i-1]){
continue;
}
for(int j = i + 1; j < len - 1;j++){
if(j != i + 1 && nums[j] == nums[j-1]){
continue;
}
int search = -(nums[i] + nums[j]);
if(midFind(nums , j+1 , len -1 , search)){
vector<int> tmp ;
tmp.push_back(nums[i]);
tmp.push_back(nums[j]);
tmp.push_back(search);
res.push_back(tmp);
}
}
}
return res;
}
};