gpt4 book ai didi

c# - 最接近值的元组的二进制搜索列表 >=

转载 作者:太空狗 更新时间:2023-10-30 01:00:13 26 4
gpt4 key购买 nike

给定一个:

List<Tuple<DateTime, int>>

其中提供的列表按 DateTimedescending 排序。

如何使用 .BinarySearch() 方法找到 DateTime>= 的值的最小索引指定值?

EG,具有以下值:

[0] = 29th Jan
[1] = 25th Jan
[2] = 20th Jan
[3] = 10th Jan
[4] = 3rd Jan

搜索结果将是:

1st Jan = return 4
5th Jan = return 3
28th Jan = return 0
1st Feb = return something else indicating nothing found (eg -1 or null)

最佳答案

由于您的列表的排序与 BinarySearch 所期望的相反,因此您的比较方法需要返回日期比较结果的倒数:

class TupleCompare : IComparer<Tuple<DateTime,int>> {
public static readonly TupleCompare Instance = new TupleCompare();
public int Compare(Tuple<DateTime,int> x, Tuple<DateTime,int> y) {
return -x.Item1.CompareTo(y.Item1); // Note the negative here
}
}

有了这个比较器,调用 BinarySearch,检查它的值是否为负,反转它的位,然后减去 1:

DateTime myDate = ... // desired date
int index = list.BinarySearch(Tuple.Create(myDate, 0), TupleCompare.Instance);
if (index < 0) {
var res = ~index-1;
} else {
Console.WriteLine("Exact match at index {0}", index);
}

Demo.

关于c# - 最接近值的元组的二进制搜索列表 >=,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48343264/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com