Find the largest value smaller than x in a sorted array

后端 未结 5 1443
不知归路
不知归路 2021-02-07 23:26

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

for example if the array contains (1)

5条回答
  •  说谎
    说谎 (楼主)
    2021-02-08 00:10

    I'd go for a linq solution (updated: to add a little more code to stop from being similar to fear's similar solution):

    int[] arr1 = { 1, 23, 57, 59, 120 };
    int maxResult;
    string errorMsg;
    try
    {
        maxResult = arr1.Where(x => x <= 109).Max();
    }
    catch(Exception e)
    {
        errorMsg = e.Message;
        // do some error stuff here :)
        return null;
    }
    // party on your maxResult...
    

提交回复
热议问题