在字典 c# 中查找与给定值最接近的值

use*_*718 2 c# dictionary numbers key-value

我有一本字典,我想找出哪个“键”值最接近给定值,下面是我的字典。

Dictionary<double, int> dictionary = new Dictionary<double, int>();

dictionary.Add(2.4, 5000);
dictionary.Add(6, 2000);
dictionary.Add(12, 1000);
dictionary.Add(24, 500);
dictionary.Add(60, 200);
dictionary.Add(120, 100);
dictionary.Add(240, 50);
dictionary.Add(600, 20);
dictionary.Add(1200, 10);
dictionary.Add(2400, 5);
dictionary.Add(6000, 2);
dictionary.Add(12000, 1);

givenValue = 1;
Run Code Online (Sandbox Code Playgroud)

所以我想找出哪个键最接近1。我需要返回键值对,所以它应该返回[2.4, 5000]。

Ale*_*lex 5

好吧,您可能会问自己,字典是否是解决这些类型问题的正确结构,但假设这是给定的(以解决其他问题),您可以执行以下操作:

var bestMatch = dictionary.OrderBy(e => Math.Abs(e.Key - givenValue)).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

如果您需要执行许多此类查询,这将非常低效。

以下是更有效的:

Tuple<double, KeyValuePair<double, int>> bestMatch = null;
foreach (var e in dictionary)
{
    var dif = Math.Abs(e.Key - givenValue);
    if (bestMatch == null || dif < bestMatch.Item1)
        bestMatch = Tuple.Create(dif, e);
}
Run Code Online (Sandbox Code Playgroud)

  • @Sharped Care 解释一下?第一个排序解决方案是 O(N log N),第二个解决方案是 O(N)。也许您指的是元组的多重分配?通过分别跟踪最佳匹配对和最小差异,可以轻松避免这些问题。 (3认同)