我有一个像这样的值列表
1000, 20400
22200, 24444
范围不重叠。
我想要做的是有一个 C# 函数,可以存储(从数据库加载的值,然后在本地缓存)这些值的相对较大的列表,然后有一个方法来查找提供的值是否在任何范围内?
这有道理吗?
需要最快的解决方案
您已经指定了值,但随后讨论了范围。
对于价值观,我会使用HashSet<int>
。对于范围,它会变得更加复杂......让我们知道这是否真的是您所追求的,我会更多地考虑它。如果他们are范围,您有关于它们的任何额外信息吗?你知道它们是否会重叠吗?您只是对某个范围的存在感兴趣,还是需要找到某个值所属的所有范围?
编辑:通过对问题的编辑,巴里的答案是完全正确的。只需在初始化时排序(按下界就足够了),然后进行二分搜索以查找包含该值或缺少该值的范围。
编辑:我在以下位置找到了代码我对类似问题的回答 https://stackoverflow.com/questions/454250#454312最近。
范围需要预先排序 -List<Range>.Sort
假设你没有重叠,就会很好地工作。
public class Range : IComparable<Range>
{
private readonly int bottom; // Add properties for these if you want
private readonly int top;
public Range(int bottom, int top)
{
this.bottom = bottom;
this.top = top;
}
public int CompareTo(Range other)
{
if (bottom < other.bottom && top < other.top)
{
return -1;
}
if (bottom > other.bottom && top > other.top)
{
return 1;
}
if (bottom == other.bottom && top == other.top)
{
return 0;
}
throw new ArgumentException("Incomparable values (overlapping)");
}
/// <summary>
/// Returns 0 if value is in the specified range;
/// less than 0 if value is above the range;
/// greater than 0 if value is below the range.
/// </summary>
public int CompareTo(int value)
{
if (value < bottom)
{
return 1;
}
if (value > top)
{
return -1;
}
return 0;
}
}
// Just an existence search
public static bool BinarySearch(IList<Range> ranges, int value)
{
int min = 0;
int max = ranges.Count-1;
while (min <= max)
{
int mid = (min + max) / 2;
int comparison = ranges[mid].CompareTo(value);
if (comparison == 0)
{
return true;
}
if (comparison < 0)
{
min = mid+1;
}
else if (comparison > 0)
{
max = mid-1;
}
}
return false;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)