gpt4 book ai didi

c# - 在排序数组中找到小于 x 的最大值

转载 作者:可可西里 更新时间:2023-11-01 08:32:19 25 4
gpt4 key购买 nike

假设我有一个排序的整数数组 int[],我想搜索最接近某个输入数字的较小值。

例如,如果数组包含 (1) , (23), (57) , (59), (120) 并且输入为 109,则输出应为 59。

我只是想看看建议并与我已有的方法进行比较。

最佳答案

使用Array.BinarySearch .如果输入在列表中,它将返回索引,如果不在列表中,则返回第一个较大值的索引的补码。您只需反转结果并减去一个以获得最接近的较小值的索引。

int[] arr = { 1, 23, 57, 59, 120 };
int index = Array.BinarySearch(arr, 109);
if (index < 0)
{
index = ~index - 1;
}
if (index >= 0)
{
var result = arr[index];
}

请注意,如果您的输入小于最小元素,则您没有明确定义的答案。

关于c# - 在排序数组中找到小于 x 的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3492840/

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