查找数组中最接近的数字

12 java

首先,我们必须在数组中查找是否存在所需的数字?如果没有,那么我如何在Java中找到给定所需数字的更接近的数字?

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)


Ant*_*lev 0

Array.indexOf()找出元素是否存在。如果不存在,则迭代数组并维护一个变量,该变量保存所需元素和i第 - 个元素之间的差的绝对值。返回绝对差值最小的元素。

总体复杂度为O(2n),可以进一步减少为数组上的单次迭代(即O(n))。不过不会有太大区别。