Find number which is greater than or equal to N in an array

前端 未结 11 1080
长发绾君心
长发绾君心 2020-11-30 05:47

If I have a PHP array:

$array

With values:

45,41,40,39,37,31

And I have a variable:

$numb         


        
11条回答
  •  半阙折子戏
    2020-11-30 06:40

    Here is a high-level process to get the desired results and work for any array data:

    • Filter the array keeping on values greater than or equal to the target and then select the lowest remaining value. This is the "best" value (which may be "nothing" if all the values were less) -- this is O(n)
    • Alternatively, sort the data first and see below -- this is O(n lg n) (hopefully)

    Now, assuming that the array is sorted ASCENDING, this approach would work:

    • Loop through the array and find the first element which is larger than or equal to the target -- this is O(n)

    And if the array is DESCENDING (as in the post), do as above, but either:

    • Iterate backwards -- this is O(n)
    • Sort it ASCENDING first (see fardjad's answer) -- this is O(n lg n) (hopefully)
    • Iterate forwards but keep a look-behind value (to remember "next highest" if the exact was skipped) -- this is O(n)

    Happy coding.

提交回复
热议问题