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

4

我有一个字典,想要找出哪个“key”值最接近给定的数值,以下是我的字典:

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;

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

1个回答

7

好的,您也许会问自己,字典是否是解决这些问题的正确结构,但假设这是一个已知条件(为了解决其他问题),您可以采取以下措施:

var bestMatch = dictionary.OrderBy(e => Math.Abs(e.Key - givenValue)).FirstOrDefault();

如果您需要执行许多这样的查询,那么这将非常低效。

以下方法更加高效:

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);
}

3
能解释一下吗?第一个排序解决方案的时间复杂度为O(N log N),第二个解决方案的时间复杂度为O(N)。也许您指的是Tuple的多次分配?可以通过单独跟踪最佳匹配对和最小差异来轻松避免这些问题。 - Alex
@Sharped,也许你应该在发表误导性评论之前先尝试一下。线性搜索选项(包括元组分配)的速度比其他方法快10倍以上。请不要轻易下投票。 - Alex
@Alex,你是对的,OrderBy是O(NlogN),我删除了无用的评论。 - rducom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接