What is performance of ContainsKey and TryGetValue

2019-04-24 11:02发布

问题:

I'm prepping for interviews, and some obvious interview questions such as counting frequency of characters in a string involve putting all of the characters into a Hashtable/Dictionary in order to get O(n) runtime for the algorithm. My question is, what is the performance hit by using ContainsKey and TryGetValue to check to see if a key has already been inserted into the Hashtable? Can I still have an O(n) algorithm for problems like these that use ContainsKey or TryGetValue?

回答1:

Assuming a good hash without too many collisions, each of those are O(1) operations.

As for how those operations work... I suggest you read up on hash tables.