找到最大的值小于x在排序后的数组 [英] Find the largest value smaller than x in a sorted array

查看:100
本文介绍了找到最大的值小于x在排序后的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose I have a sorted array of integers int[], and I want to search the closest smaller value to some input number.

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

for example if the array contains (1) , (23), (57) , (59), (120) and the input is 109, the output should be 59.

我只是想看看的建议,并比较我已经有办法。

I am just trying to see suggestions and compare to the approaches I already have.

推荐答案

使用 Array.BinarySearch 。如果输入是在列表中,它会返回的索引,并且如果没有,那么它将返回第一较大值的索引的补码。你只是反转的结果,减去一个拿到最接近的较小值的索引。

Use Array.BinarySearch. If the input is in the list, it will return the index, and if not then it will return the complement of the index of the first larger value. You just invert the result and subtract one to get the index of the closest smaller value.

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];
}

请注意,如果你有比的最小元素小的投入,你没有一个明确的答案。

Note that if you have an input smaller than the smallest element, you don't have a well-defined answer.

这篇关于找到最大的值小于x在排序后的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆