我有一本字典;
Dictionary<int, float> delta = new Dictionary<int, float>();
其中包含:
0, 45,2345
7, 25,3556
18, 23,2334
如何找到最接近数字的下键?
想象一下,我有数字16,id喜欢找到键7的值。对于4,id类似,喜欢键0的值。
最好我也想以最快的方式做到这一点,因为我必须运行该操作数百万次。
我使用C#、. NET 4。
您可以过滤键,只保留较低的键,然后获得最大键:
Dictionary<int, float> delta = new Dictionary<int, float>();
var key = 16;
var maxKey = delta.Keys.Where(k => k < key).Max();
var value = delta[maxKey];
但是,如注释中所述,更好的方法是使用类SortedDictionary<>
或SortedList<>
。
如果首先运行所有添加/删除操作,然后仅执行搜索,则可以将键转换为数组(O(N))和使用Array.BinarySearch()
方法(O(log N)):
SortedDictionary<int, float> sortedDict = new SortedDictionary<int, float>();
// Add-Remove operations
var keys = sortedDict.Keys.ToArray();
// Search operations
int maxKey = Array.BinarySearch(keys, key);
float value = maxIndex >= 0 ? sortedDict[maxKey] : sortedDict[~maxIndex - 1];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句