I was solving a competitive programming problem on interviewbit.com I basically used a unordered_map to keep track of visited numbers. When I used operator[], my code could not perform in time, but it passes all tests when I used find. Both should have same time complexity.
I tried timing both codes using clock() by running them 10 times and averaging out the run times and they both gave more or less same time. I used g++ 7.4.0 while the environment provided by website has g++ 4.8.4. Could this be the reason for this.
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;
}
The problem was to find pairs in array whose sum also exist in the array. I got "time limit exceeded" on array size of about 900 when I used the [] operator.
There are two reasons why the []-operator will be slower than find:
I think your performance measurements showed no difference between the two alternatives because of one or more of this reasons:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With