What is the lookup time complexity of HashSet(IEqualityComparer)?

后端 未结 5 2086
无人及你
无人及你 2020-12-05 14:39

In C#.NET, I like using HashSets because of their supposed O(1) time complexity for lookups. If I have a large set of data that is going to be queried, I often prefer using

5条回答
  •  渐次进展
    2020-12-05 15:12

    Actually the lookup time of a HashSet isn't always O(1).

    As others have already mentioned a HashSet uses IEqualityComparer.GetHashCode().
    Now consider a struct or object which always returns the same hash code x.

    If you add n items to your HashSet there will be n items with the same hash in it (as long as the objects aren't equal).
    So if you were to check if an element with the hash code x exists in your HashSet it will run equality checks for all objects with the hash code x to test wether the HashSet contains the element

提交回复
热议问题