在一个数组中,我们首先要找出其中是否存在一个所需的数字?如果不是,那么我如何在Java中找到更接近给定期望数字的数字呢?
发布于 2009-02-06 03:07:43
一个想法:
int nearest = -1;
int bestDistanceFoundYet = Integer.MAX_INTEGER;
// We iterate on the array...
for (int i = 0; i < array.length; i++) {
// if we found the desired number, we return it.
if (array[i] == desiredNumber) {
return array[i];
} else {
// else, we consider the difference between the desired number and the current number in the array.
int d = Math.abs(desiredNumber - array[i]);
if (d < bestDistanceFoundYet) {
// For the moment, this value is the nearest to the desired number...
bestDistanceFoundYet = d; // Assign new best distance...
nearest = array[i];
}
}
}
return nearest;
发布于 2009-02-06 05:04:11
“更近”的另一个常见定义是基于差异的平方。该大纲类似于romaintaz提供的大纲,不同之处在于您要计算
long d = ((long)desiredNumber - array[i]);
然后将(d * d)
与最近的距离进行比较。
请注意,我键入d
作为long
而不是int
是为了避免溢出,即使使用基于绝对值的计算也可能发生溢出。(例如,考虑当desiredValue
至少是最大32位有符号值的一半,并且数组包含一个具有相应大小但负号的值时,会发生什么情况。)
最后,我会编写方法来返回值的索引,而不是返回值本身。在这两种情况中的任何一种:
如果数组的长度为零,则返回
”参数,则返回
与indexOf
上的等级库类似,您可以使用-1
作为带外值。
发布于 2014-09-26 09:44:13
//这样就可以了
public int nearest(int of, List<Integer> in)
{
int min = Integer.MAX_VALUE;
int closest = of;
for (int v : in)
{
final int diff = Math.abs(v - of);
if (diff < min)
{
min = diff;
closest = v;
}
}
return closest;
}
https://stackoverflow.com/questions/519881
复制