algorithm - why '*' faster than hash find, c++ -


i learnt data structure, can tell me why hash slow, thank you!

this problem leetcode: https://leetcode.com/problems/happy-number/

bool ishappy(int n) {     unordered_map<int, int> m;     m[0] = 0, m[1] = 1, m[2] = 4, m[3] = 9, m[4] = 16, m[5] = 25,\     m[6] = 36, m[7] = 49, m[8] = 64, m[9] = 81;     int temp, mark = 0;   //temp next n, mark detect circle      while(n){         temp = 0;         if(n == 1) return true;         if(n < 10){             if(mark == n)                return false;             mark = n;         }         //calc next n         while(n){             temp += (n%10)*(n%10); // 4 ms             //temp += m[n%10];       // 8 ms             n /= 10;         }         n = temp;     } } 

why not? hashing efficient because of constant fetch time on average. that's it.

there no guarantee it's faster *. note key not directly used key hash table(this called "direct-address table" has own drawbacks). in general, there calculation key hash key: hash_key = hash(your_key). time totally depends on how hash implemented. once hash key calculated, it's matter of indexing table.

as matter of fact, common implementation of hashing involves modulus(%) operation slower '*'. think this: c = % b equivalent c = – b * (a / b).

you might ask 2 %(as in * case) vs 1 %(as in map case)? guess n%10 optimized compute once in first case.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -