2017-04-25 28 views
-4

我正在做3sum问题在leetcode.com3etum LTE leetcode

蛮力的时间复杂度是O(N^3)。

我使用哈希表,所以我认为时间复杂度是O(N^2)。

然而,我仍然有一个TLE(超出时间限制)

我怎样才能加快我的代码?

以下是我的代码

非常感谢!

class Solution public: 
vector<vector<int>> threeSum(vector<int>& nums) { 

    vector<vector<int>> ANS; 
    if(nums.size() < 3) return ANS; 

    map<int,int*> hashtable; 
    map<int,int*>::iterator it; 
    vector<int> ans; 

    for(int i=0;i < nums.size();i++) 
    { 

     for(int j=i+1;j < nums.size();j++) 
     { 

      it = hashtable.find(nums[j]); 
      if(it != hashtable.end()) //found target 
      { 
       ans.push_back(nums[j]); 
       ans.push_back((it)->second[0]); 
       ans.push_back((it)->second[1]); 
       sort(ans.begin(),ans.end()); 
       ANS.push_back(ans); 

       ans.clear(); 

      } 
      else 
      { 
       int* temp = new int[2]; 
       temp[0]=nums[i]; 
       temp[1]=nums[j]; 
       hashtable[0-nums[i]-nums[j]]=temp; 

      } 
     } 
     hashtable.clear(); 

    } 
    sort(ANS.begin(), ANS.end()); 
    ANS.erase(unique(ANS.begin(), ANS.end()), ANS.end()); 
    return ANS; 
}}; 
+3

询问改善工作代码的问题应该在[代码评论](https://codereview.stackexchange.com/)上提问 – NathanOliver

+0

对不起,我将删除该文章 – Frank

回答

0

您的解决方案是不是真的O(n^2),它肯定比O(n^2)昂贵。而在没有任何优化的O(n^2)解决方案将不会通过OJ。这是我的解决方案,它是O(n^2)。我已经在代码中加入了解释的评论。

vector<vector<int> > threeSum(vector<int> &num) { 
    vector <vector<int> > result; 
    size_t n = num.size(); 
    if(n < 3) return result; 

    vector<int> solution(3); 
    sort(num.begin(), num.end()); 
    for(int i = 0; i < n - 2; ++i) { 
     int start = i + 1, end = n - 1; 

     while(start < end) { 
      int sum = num[start] + num[end] + num[i]; 
      if(sum == 0) { 
       solution.at(0) = num[i]; 
       solution.at(1) = num[start]; 
       solution.at(2) = num[end]; 
       result.push_back(solution); 
       // these loops will skip same elements and fasten the algorithm 
       // while(start < n - 1 and num[start] == num[start + 1]) start++; 
       // while(end > i + 1 and num[end] == num[end - 1]) end--; 
       start++, end--; 
      } else if(sum > 0) { 
       // while(end > i + 1 and num[end] == num[end - 1]) end--; 
       end--; 
      } else { 
       // while(start < n - 1 and num[start] == num[start + 1]) start++; 
       start++; 
      } 
     } 
     while(i < n - 1 and num[i] == num[i + 1]) i++; 
    } 

    return result; 
} 

让我知道你是否有任何问题。希望能帮助到你!

+0

真的帮了我很多!不错 – Frank