【问题标题】:How to get range key of specific value in sortedList如何在 sortedList 中获取特定值的范围键
【发布时间】:2020-08-22 14:28:22
【问题描述】:

我想从 sortedlist 或其他类似的排序数据结构中获取范围键。

例如;

                SortedList<long, string> testSorted = new SortedList<long, string>();
                testSorted.Add(1, "a");
                testSorted.Add(4, "b");
                testSorted.Add(15, "c");

                testSorted.Add(12, "d");
                testSorted.Add(10, "e");
                testSorted.Add(8, "f");

                int wantspecifickey = 7;

                int index = testSorted.GetClosestIndex(wantspecifickey);
                int range = 1;
                List<long> rangeIndex = testSorted.GetRangeIndexKey(index , range);

最接近 7 的键值为 8。

所以索引值为2。

之后,在索引 2(key: 8)处,索引范围 1 内的索引的键是 4 8 和 10。

你们有什么好主意来解决我的问题吗?

PS。我不必使用排序列表。如果有更高效的数据结构,也请告诉我。

【问题讨论】:

  • 尝试使用 SortedSet 它有 GetViewBetween 方法和其他有用的方法,可以帮助您解决这个问题

标签: c# indexing data-structures key sortedlist


【解决方案1】:

这是我的两分钱;

public class Program
{
    public static Tuple<int, int, int> FindClosestRange(int[] keys, int key)
    {
        if (keys == null)
            throw new ArgumentNullException(nameof(keys));
        if (keys.Length == 0)
            throw new ArgumentException();
        
        Array.Sort(keys);
        var minDiff = int.MaxValue;
        var minIndex = 0;
        for(var index = 0; index < keys.Length;index++)
        {
            var diff = Math.Abs(keys[index] - key);
            if (diff < minDiff)
            {
                minDiff = diff;
                minIndex = index;
            }
        }
        var lowerBoundry = Math.Max(minIndex - 1, 0);
        var higherBoundry = Math.Min(minIndex + 1, keys.Length - 1);
        
        return Tuple.Create(keys[lowerBoundry], keys[minIndex], keys[higherBoundry]);
    }
    
    public static void Main()
    {
        var list = new Dictionary<int, string>()
        {
            { 1, "a" },
            { 4, "b" },
            {10, "e"},
            { 15, "c" },
            {8, "f"},
            { 12, "d"},
        };

        var range = FindClosestRange(list.Keys.ToArray(), 7);
        Console.WriteLine($"Closest {range}");
    }
}

它不使用排序列表,而是使用字典。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    相关资源
    最近更新 更多