【问题标题】:Find closest value to a given value in a dictionary c#在字典c#中查找最接近给定值的值
【发布时间】:2015-04-24 06:03:08
【问题描述】:

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

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]。

【问题讨论】:

    标签: c# dictionary numbers key-value


    【解决方案1】:

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

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

    【讨论】:

    • @Sharped Care 解释一下?第一个排序解决方案是 O(N log N),第二个解决方案是 O(N)。也许您指的是元组的多个分配?通过分别跟踪最佳匹配对和最小差异,可以轻松避免这些问题。
    • @Sharped,也许您应该尝试一下,然后再投反对票并在没有解释的情况下发布误导性的 cmets。线性搜索选项(包括元组分配)快 10 倍以上。
    • @Alex,你是对的,OrderBy 是 O(NlogN),我删除了我无用的评论
    猜你喜欢
    • 2017-01-23
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    相关资源
    最近更新 更多