如何在sortedList中获取特定值的范围键

问题描述

我想从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(键:8)处,索引范围1内的索引键为4 8和10。

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

PS。我不必使用sortedlist。如果有更有效的数据结构,请也告诉我。

解决方法

这是我的两分钱

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

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