15. 3Sum
原题目:
读题:
任意三个数相加为0,但是不能是相同的三元组
解题思路:
先排序,然后遍历序列,如果遇到相同的数则跳过,指定一个num[i]后,剩下的就是要找到另外两个数A+B=-num[i],可以采用二分查找,begin = i+1;end = len -1;依次查找可以得到,以下是AC代码
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { int i,j,k; int sum,begin,end; vector <vector<int>> result; int length = nums.size(); if(length < 3) { return result; } sort(nums.begin(),nums.end()); for(i=0;i<length;i++) { if(nums[i]>0) { break; } if( i > 0 && nums[i] == nums[i-1]) { continue; } begin = i+1; end = length-1; while(begin < end) { sum = nums[i] + nums[begin] + nums[end]; if (0 == sum) { vector <int> temp; temp.push_back(nums[i]); temp.push_back(nums[begin]); temp.push_back(nums[end]); result.push_back(temp); begin++; end--; while(begin < end &&nums[begin] == nums[begin-1]) { begin++; } while(begin < end &&nums[end] == nums[end+1]) { end--; } } else if(sum>0) { end--; } else { begin++; } } } return result; } }; int main() { Solution s; int i,j; vector <vector <int>> result; vector <int> v; v.push_back(-1); v.push_back(0); v.push_back(1); v.push_back(2); v.push_back(-1); v.push_back(-4); result = s.threeSum(v); for(i=0;i<result.size();i++) { for(j=0;j<result[i].size();j++) { cout<<result[i][j]<<endl; } } }