Rom*_*las 12
一个主意:
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;
Run Code Online (Sandbox Code Playgroud)
Array.indexOf()
找出元素是否存在。如果不存在,则迭代数组并维护一个变量,该变量保存所需元素和i
第 - 个元素之间的差的绝对值。返回绝对差值最小的元素。
总体复杂度为O(2n),可以进一步减少为数组上的单次迭代(即O(n))。不过不会有太大区别。
归档时间: |
|
查看次数: |
24804 次 |
最近记录: |