标签:des style blog io ar color sp for on
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:
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
class Solution { public: vector<vector<int> > threeSum(vector<int> &num) { vector<vector<int>> ret; if(num.size() < 3) return ret; sort(num.begin(), num.end()); for(int i = 0; i < num.size() - 2; ++i){ int left = i + 1; int right = num.size() - 1; while(left < right){ if(num[left] + num[right] + num[i] > 0){ --right; }else if(num[left] + num[right] + num[i] < 0){ ++left; }else{ ret.push_back(vector<int>{num[i], num[left], num[right]}); while(right > left && num[right] == num[(right--) - 1]) //num[right]为最后一个重复元素,并且对right自减,left同理 ; while(left < right && num[left] == num[(left++) +1]) ; } } while(i < num.size() - 1 && num[i + 1] == num[i]) ++i; } return ret; } };
标签:des style blog io ar color sp for on
原文地址:http://www.cnblogs.com/64open/p/4148949.html