Contents

Close number(with.Java)

   Feb 21, 2024     2 min read

This article examines the “close number” problem.

As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.

Let’s look at the problem first.

problem

When an integer array array and an integer n are given as parameters, complete the solution function so that it returns the number closest to n among the integers contained in the array.

Restrictions

  • 1 ≤ length of array ≤ 100
  • 1 ≤ element of array ≤ 100
  • 1 ≤ n ≤ 100
  • If there are multiple closest numbers, the smaller number is returned.

Input/Output Example

sresult
“1 2 Z 3”4
“10 20 30 40”100
“10 Z 20 Z 1”1

My solution to the problem

import java.util.*;
class Solution {
     public int solution(int[] array, int n) {
         int answer = 0;
         int temp = 101;
         Arrays.sort(array);
         for(int i = 0; i < array.length; i++){
             if(temp > Math.abs(n - array[i])){
                 answer = array[i];
                 temp = Math.abs(n - array[i]);
             }
         }
         return answer;
     }
}

Solution explanation

  • Initial value setting: Initialize the temp variable to 101. This value is set to be greater than the maximum difference of array elements.
  • Sorting an array: Use the Arrays.sort method to sort an array in ascending order.
  • Array traversal: Calculate the difference between each element and n while traversing the sorted array.
  • Find the closest element: If a difference smaller than the minimum difference so far appears, the element is assigned to the answer and the temp value is updated.
  • Return result: Returns the closest element if found.

Code Advantages

  • Utilize ascending sort: You can use a sorted array to efficiently find the element closest to n.
  • Concise Logic: Simple yet effective logic to find the closest array element.

Code Disadvantages

  • Fixed initial value: The initial value 101 is determined by the maximum difference between array elements. If the values in the array are out of range, you must adjust these values appropriately.
  • No handling when the array is empty: The current code does not take into account handling when the array is empty. I would recommend adding handling for empty arrays.
  • No handling when there are multiple minimum differences: The current code does not handle cases where there are multiple minimum differences. For example, if the array is [1, 5, 9] and n is 6, both 5 and 9 have the minimum difference. I would recommend adding handling for this.