如何快速是KeyCollection操作由Dictionary.Keys返回? (。净)快速、操作、Keys、KeyCollection

2023-09-03 15:10:27 作者:回忆是张网困住现在和未来

的IDictionary< TK,电视> 定义方法 IDictionary.ContainsKey(在TK) 和财产 IDictionary.Keys 。 我感兴趣的是这种方法和属性的 词典 实施 的IDictionary< TK,电视>

考虑定义

 的IDictionary< INT,字符串>字典=新字典< INT,字符串>();
INT K =新的随机()下()。
 

和考虑,我们已经添加到字典字典 N 唯一 KeyValuePair 秒。

什么是预期呼叫 dict.ContainsKey(k)的(渐近)的复杂性?我希望它在 O(1),但我没有找到它的 Dictionary.ContainsKey

通话的期望是什么(渐近)的复杂性 dict.Keys.Contains(K)?我希望它在 O(1),但我没有找到它的的文档 Dictionary.Keys 也不在的 Dictionary.KeyCollection 的文档。如果是在 O(1)我不明白,为什么类型 IDictionary.Keys 属性的ICollection ,而不是的ISet (类似于Java为例)。

解决方案

由于的IDictionary< K,V> 只是一个接口,而不是实现,那么它不牛逼提供任何的性能保证。

C 中 ConcurrentDictionary 一定线程安全吗

有关内置词典< K,V> 键入时,的 的containsKey 的方法应该是O(1):

  

这种方法接近一个O(1)操作。

借助 Keys.Contains 方法实际上调用父字典的的containsKey 的方法,这样也应该是O(1):

  

这种方法复杂度为O(1)操作。

(两个引号是取自备注的相关文档页面的部分。)的

IDictionary<TK, TV> defines method IDictionary.ContainsKey(in TK) and property IDictionary.Keys (of type ICollection). I'm interested in (asymptotic) complexity of this method and property in Dictionary implementation of IDictionary<TK, TV>.

Consider definitions

IDictionary<int, string> dict = new Dictionary<int, string>();
int k = new Random().Next();

and consider that we have added to the dictionary dict n unique KeyValuePairs.

What is expected (asymptotic) complexity of a call dict.ContainsKey(k)? I hope it's in O(1) but I did not find it in documentation of Dictionary.ContainsKey.

What is expected (asymptotic) complexity of call dict.Keys.Contains(k)? I hope it's in O(1)but I did not find it in documentation of Dictionary.Keys nor in documentation of Dictionary.KeyCollection. If it is in O(1) I don't understand why type of IDictionary.Keys property is ICollection and not ISet (like in Java for example).

解决方案

Since IDictionary<K,V> is only an interface, not an implementation, then it doesn't provide any performance guarantees.

For the built-in Dictionary<K,V> type, the ContainsKey method should be O(1):

This method approaches an O(1) operation.

The Keys.Contains method actually calls the parent dictionary's ContainsKey method, so that should also be O(1):

This method is an O(1) operation.

(Both quotes are taken from the "Remarks" section of the relevant documentation pages.)