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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Pseudocode to return list of closest integers.
Only thing missing is the semantics of closer.
What do you do if you're looking for six and your array has both four and eight?
Which one is closest?
If the array is sorted, then do a modified binary search. Basically if you do not find the number, then at the end of search return the lower bound.
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 andi
-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.
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
and then compare
(d * d)
to the nearest distance.Note that I've typed
d
aslong
rather thanint
to avoid overflow, which can happen even with the absolute-value-based calculation. (For example, think about what happens whendesiredValue
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:
you can use
-1
as an out-of-band value similar to the spec onindexOf
.