Find the largest value smaller than x in a sorted array

后端 未结 5 1446
不知归路
不知归路 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

    just to extrapolate on the other LINQ solutions this extension method will return -1 if no objects fits the filter and expects that the list is all positive integers

    public static int SearchForLimit(this IEnuemerable sequence, Predicate filter)
    {
       return (from i in sequence
               let n = filter(i) ? i : -1
               select n).Max()
    }
    

    usage would look like this:

    int[] arr1 = { 1, 23, 57, 59, 120 };
    int limitedBy109 = arr1.SearchForLimit(i => i < 109);
    

提交回复
热议问题