我在interviewbit.com上解决了一个竞争编程问题。我基本上使用unordered_map来跟踪已访问的数字。当我使用operator[]时,我的代码不能按时执行,但是当我使用find时,它可以通过所有测试。它们都应该具有相同的时间复杂度。
我尝试使用clock()计时两个代码,每个运行10次并平均运行时间,它们都给出了更多或更少相同的时间。我使用g ++ 7.4.0,而网站提供的环境具有g ++ 4.8.4。这可能是原因。
我尝试使用clock()计时两个代码,每个运行10次并平均运行时间,它们都给出了更多或更少相同的时间。我使用g ++ 7.4.0,而网站提供的环境具有g ++ 4.8.4。这可能是原因。
int Solution::solve(vector<int> &A) {
unordered_map<long long, int> hashmap;
for(auto a : A)
hashmap[a] = 1;
int res = 0;
for(int i = 0; i < A.size(); ++i){
for(int j = i + 1; j < A.size(); ++j){
// if(hashmap.find((long long)A[i] + A[j]) != hashmap.end())
if(hashmap[(long long)A[i] + A[j]] == 1)
++res;
}
}
return res;
}
这个问题是在数组中找到一对数,它们的和也存在于该数组中。当我使用[]操作符时,在数组大小约为900时,我遇到了“超时”错误。
unordered_set
是解决这个问题的正确数据结构。 - Omnifarious