如何解决如何在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}");
}
}
它不使用排序列表,而是使用字典。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。