标签:
Title:
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)
//68ms class Solution { public: vector<vector<int> > threeSum(vector<int> &num) { std::sort(num.begin(), num.end()); int target1 = 0; vector<int> every_vec; vector<vector<int> > final_vec; if (num.size() <= 2) return final_vec; //corner case: for (int i = 0; i < num.size() - 2; ++i) { if(i > 0 && num[i] == num[i - 1]) continue; target1 = 0 - num[i]; int first = i + 1; int last = num.size() - 1; while (first < last) { if (num[first] + num[last] < target1) { while (first < num.size() - 1 && num[first] == num[first + 1]) first++; first++; }else if (num[first] + num[last] > target1) { while (last > 0 && num[last] == num[last - 1]) last--; last--; }else { every_vec.clear(); every_vec.push_back(num[i]); every_vec.push_back(num[first]); every_vec.push_back(num[last]); final_vec.push_back(every_vec); while (first < num.size() - 1 && num[first] == num[first+1]) first++; while (last > 0 && num[last] == num[last - 1]) last--; first++; last--; } } } return final_vec; } };
标签:
原文地址:http://www.cnblogs.com/yxzfscg/p/4419191.html