I was solving a problem on LeetCode called "Longest Substring Without Repeating Characters"
and I know that
- insertion and searching in Hash Map
is O(1), for n times is O(n)
- insertion and searching in Map
is O(log n), for n times O(nlog(n))
but when I was using hash map
(unorderd_map) in cpp, the run time was 140ms
and when using map
in cpp, the run time was 40ms
code below using hash map runs in 140ms:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int start=0, mx=0;
unordered_map<char, int>um;
for(int i=0; i<s.size(); i++)
{
if(um.count(s[i]) && start<=um[s[i]])//exists
start=um[s[i]]+1;
else
mx=max(mx, i-start+1);
um[s[i]]=i;
cout<<mx<<"\n";
}
return mx;
}
};
and the same code with replacing hash map "unordered_map" with map runs in 40ms
so Why did this happen and not the opposite?