How to find the next largest key in the collection?

Suppose I have a dictionary in C #. Assuming the keys are comparable, how do I find the smallest key different from the given k (the same type as the dictionary keys)? However, I would like to do this efficiently with a collection like SortedDictionary.

It is clear that if there was no effective solution, you can start with any dictionary, extract its keys, and then use the First method with a suitable predicate. But this will be done in linear time (in the number of keys), if, if you have a sorted set of keys, you must find the key in the time log.

Thank.

+3
source share
4 answers

SortedList<TKey, TValue> IDictionary<TKey, TValue> IndexOfKey; , :

// I'm just going to pretend your keys are ints
var collection = new SortedList<int, string>();

// populate collection with whatever

int k = GetK(); // or whatever

int kIndex = collection.IndexOfKey(k);

int? smallestKeyGreaterThanK = null;
if (collection.Count > kIndex + 1)
    smallestKeyGreaterThanK = collection.Keys[kIndex + 1];

MSDN:

; O (log n).

EDIT. , , ( - ), .NET . , "" ; , ( ). , , . :

List<int> keysList = new List<int>(collection.Keys);
int kIndex = keysList.BinarySearch(k);

BinarySearch , , , . MSDN :

List<T>, ; - , , , .

, :

kIndex = kIndex >= 0 ? kIndex : ~kIndex;
+4

, , , .

(n * log (n)) + log (n) .

, log (n), .

, f (n) vs f ((n * log (n)) + log (n)) , .

f (n) f ((n * log (n))), .

+1

, SortedDictionary ? Microsoft, , .

.

br,

0

SortedDictionary IEnumerable, , k? , , . ?

0

Source: https://habr.com/ru/post/1726748/


All Articles