Finding closest number in an array

前端 未结 11 1018
萌比男神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条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-31 22:32

    An idea:

    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;
    

提交回复
热议问题