Find the largest value smaller than x in a sorted array

后端 未结 5 1447
不知归路
不知归路 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-07 23:59

    using Linq:

    int[] arr = new[] { 1, 23, 57, 59, 120 };
    int target = 109;
    int max = arr.Where(n => n < target).Max();
    

    Maybe not the fastest but probably the easiest to implement. Also doesn't rely on the array being sorted, as binary search does.

    Note that the call to Max will throw an exception if the Where filter results in no elements, so you might want to check that if it's a possibility.

提交回复
热议问题