我有一个随机数字列表,说1,8,13,20,25,32,50,55,64,70现在给定一个数字说35,所需的较小值将是32而较大值将是50。
我尝试执行此操作的方法是迭代所有值
var value = 35;
var list = new List<int> { 1, 8, 13, 20, 25, 32, 50, 55, 64, 70 };
var lesser = list.First();
var greater = list.Last();
foreach (var curr in list)
{
if (curr >= value)
{
greater = curr;
break;
}
lesser = curr;
}
Console.WriteLine("Lesser Value :{0}\tGreater Value:{1}", lesser, greater);
现在,我问这个问题的原因是,我需要针对一次生成列表然后多次请求值的情况进行优化。遍历每个请求的列表似乎是个坏主意。
更新
问题没有指定如果我们获得完全匹配,则需要什么,在这种情况下,我需要将上下限作为匹配的元素,即,在上面的列表中,32应该返回32作为较小的值,而32应该返回较大的值。
修改后的反映出来的答案是:
int value = 32;
int[] list = new[] { 1, 8, 13, 20, 25, 32, 50, 55, 64, 70 };
int? floor = null;
int? ceil = null;
int index = Array.BinarySearch(list, value);
if (index >= 0) // element is found
{
floor = ceil =list[index] ;
}
else
{
index = ~index;
if (index == list.Length)
{
ceil = floor = list[index-1];
}
else
{
ceil = list[index];
floor = list[((index==0)?index: index-1)];
}
}
Console.WriteLine("floor = {0}", floor);
Console.WriteLine("ceil = {0}", ceil);
int value = 35;
int[] list = new[] { 1, 8, 13, 20, 25, 32, 50, 55, 64, 70 };
int? floor = null;
int? ceil = null;
int index = Array.BinarySearch(list, value);
if (index >= 0) // element is found
{
if (index > 0)
floor = list[index - 1];
if (index < list.Length - 1)
ceil = list[index + 1];
}
else
{
index = ~index;
if (index < list.Length)
ceil = list[index];
if (index > 0)
floor = list[index - 1];
}
Console.WriteLine("floor = {0}", floor);
Console.WriteLine("ceil = {0}", ceil);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句