思路
- 直接暴力,(O(n^4 log(n))),不出意外的超时了。。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
int i,j,k;
int len = nums.size();
for(i = 0; i < len; i++){
for(j = i+1; j < len; j++){
for(k = j+1; k < len; k++){
if(nums[i]+nums[j]+nums[k] == 0){
vector<int> inRes;
inRes.push_back(nums[i]);
inRes.push_back(nums[j]);
inRes.push_back(nums[k]);
bool ok = true;
for(int m = 0; m < res.size(); m++){
if(issame(inRes,res[m])){
ok = false;
continue;
}
}
if(ok) res.push_back(inRes);
}
}
}
}
return res;
}
bool issame(vector<int> a,vector<int> b){
if(a.size() != b.size()) return false;
sort(begin(a),end(a));
sort(begin(b),end(b));
bool ok = true;
for(int i = 0; i < a.size(); i++){
if(a[i] != b[i]){
ok = false;
}
}
return ok;
}
};
- 利用map暴力,时间复杂度 (O(n^3 log(n))),依然超时。。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
map<int,int> tmp;
int i,j,k;
int len = nums.size();
for(i = 0; i < len; i++){
tmp[nums[i]] = i;
}
for(i = 0; i < len; i++){
for(j = i+1; j < len; j++){
vector<int> inRes = {};
if(tmp.find(-(nums[i]+nums[j])) != tmp.end() && tmp[-(nums[i]+nums[j])] != i && tmp[-(nums[i]+nums[j])] != j){
inRes.push_back(nums[i]);
inRes.push_back(nums[j]);
inRes.push_back(-(nums[i]+nums[j]));
bool ok = true;
for(int m = 0; m < res.size(); m++){
if(issame(inRes,res[m])) ok = false;
}
if(ok){
res.push_back(inRes);
}
}
}
}
return res;
}
bool issame(vector<int> a,vector<int> b){
if(a.size() != b.size()) return false;
sort(begin(a),end(a));
sort(begin(b),end(b));
bool ok = true;
for(int i = 0; i < a.size(); i++){
if(a[i] != b[i]){
ok = false;
}
}
return ok;
}
};
- 利用3个指针,首先固定一个,然后类似于Two Sum问题。(这里是用map存储返回结果的,需要避免重复的问题,而直接用set存储就方便许多了),复杂度为 (O(n^2)),如果用set的话,复杂度应该是 (O(n^3))
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int i,lo,hi;
int len = nums.size();
sort(nums.begin(), nums.end());
vector<vector<int>> res;
for(int i = 0; i < len-2; i++){
int lo = i+1,hi = len-1;
int sum = -nums[i];
if(i == 0 || (nums[i] != nums[i-1] && i > 0)){
while(lo < hi){
if((nums[lo] + nums[hi]) == sum){
vector<int> tmp;
tmp.push_back(nums[i]);
tmp.push_back(nums[lo]);
tmp.push_back(nums[hi]);
cout << tmp[0] << " " << tmp[1] <<" " << tmp[2] << endl;
res.push_back(tmp);
while(lo < hi && nums[lo] == nums[lo+1]){
lo++;
}
while(lo < hi && nums[hi] == nums[hi-1]){
hi--;
}
lo++;hi--;
}
else if ((nums[lo]+nums[hi]) < sum)
{
lo++;
}else hi--;
}
}
}
return res;
}
};