标签:
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)
思路:思路简单,注意重复项的处理
//超时 vector<vector<int> > threeSum(vector<int> &num) { vector<vector<int> > ResultVector; vector<int> VectorOne; sort(num.begin(), num.end()); for (int first = 0; first != num.size(); ++first){ if (num[first] > 0) break; for (int second = first + 1; second < num.size(); ++second){ for (int third = second + 1; third < num.size(); ++third){ int sum = num[first] + num[second] + num[third]; if (sum == 0) { VectorOne.push_back(num[first]); VectorOne.push_back(num[second]); VectorOne.push_back(num[third]); ResultVector.push_back(VectorOne); VectorOne.clear(); } } } } sort(ResultVector.begin(), ResultVector.end(), less<vector<int> >()); vector<vector<int> >::iterator new_end = unique(ResultVector.begin(), ResultVector.end()); ResultVector.erase(new_end, ResultVector.end()); return ResultVector; } //AC vector<vector<int> > threeSum(vector<int> &num) { vector<vector<int> > ResultVector; vector<int> VectorOne; sort(num.begin(), num.end()); if (num.size()<3) return ResultVector; for (int first = 0; first <= num.size() - 3; ++first){ if (num[first] > 0) break; if (first != 0 && num[first] == num[first - 1]) continue; int second = first + 1; int third = num.size() - 1; while (second < third) { int sum = num[first] + num[second] + num[third]; if (sum == 0) { VectorOne.push_back(num[first]); VectorOne.push_back(num[second]); VectorOne.push_back(num[third]); ResultVector.push_back(VectorOne); VectorOne.clear(); second++; third--; while (second < third&&num[second] == num[second - 1]) second++; while (second < third&&num[third] == num[third + 1]) third--; } else if (sum > 0) third--; else second++; } } return ResultVector; }
标签:
原文地址:http://blog.csdn.net/li_chihang/article/details/44044915