Find the number in an array that is closest to a given number

后端 未结 7 692
温柔的废话
温柔的废话 2021-01-03 23:07

I have an Array of integers in javascript, [5,10,15,20,25,30,35] when given a number x, how can I find the element in the array that is closest to that number?

相关标签:
7条回答
  • 2021-01-03 23:43

    Assuming the array is sorted, step through each adjacent pair of integers in the array. For each pair (say "5 and 10" or "20 and 25"), test if x is in between them, and if so, return whichever one is closer to x (with a bias towards the lower one).

    You would also need a special case for when x is less than the first number (return the first number) or greater than the last number (return the last number).

    If the array is not sorted, sort it first.

    0 讨论(0)
提交回复
热议问题