Finding closest number in an array

前端 未结 11 904
萌比男神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条回答
  •  闹比i
    闹比i (楼主)
    2021-01-31 22:49

    Another common definition of "closer" is based on the square of the difference. The outline is similar to that provided by romaintaz, except that you'd compute

    long d = ((long)desiredNumber - array[i]);
    

    and then compare (d * d) to the nearest distance.

    Note that I've typed d as long rather than int to avoid overflow, which can happen even with the absolute-value-based calculation. (For example, think about what happens when desiredValue is at least half of the maximum 32-bit signed value, and the array contains a value with corresponding magnitude but negative sign.)

    Finally, I'd write the method to return the index of the value located, rather than the value itself. In either of these two cases:

    • when the array has a length of zero, and
    • if you add a "tolerance" parameter that bounds the maximum difference you will consider as a match,

    you can use -1 as an out-of-band value similar to the spec on indexOf.

提交回复
热议问题