Finding closest number in an array

前端 未结 11 1106
萌比男神i
萌比男神i 2021-01-31 22:10

In an array first we have to find whether a desired number exists in that or not? If not then how will I find nearer number to the given desired number in Java?

11条回答
  •  误落风尘
    2021-01-31 22:45

    Array.indexOf() to find out wheter element exists or not. If it does not, iterate over an array and maintain a variable which holds absolute value of difference between the desired and i-th element. Return element with least absolute difference.

    Overall complexity is O(2n), which can be further reduced to a single iteration over an array (that'd be O(n)). Won't make much difference though.

提交回复
热议问题