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

后端 未结 7 693
温柔的废话
温柔的废话 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:30

    Your example list is sorted. If this is always the case, then binary search for your number. If you don't find the exact number, make the binary search end off by checking the two numbers around where the number would be and return the closest. Be careful with edge cases where all numbers are greater or are all smaller than the target number

    If the list isn't always sorted, then go through the list keeping track of the largest number <= the target number and the smallest number >= the target number. Return the one that's closest to the target.

    In either solution, you'll need to decide which side to favour if for example you're searching for 2 in [1, 3].

提交回复
热议问题