Search code examples
javaarraysmin

How to find closest number in array above target?


I use this code to find closest number in array, but this method also return number below target number. So if target is 5 and array have 4 a 7 it will return 4. How can i change this code to show clostest number above target.

    public static int findClosest(Integer[] arr, int target) {
        int idx = 0;
        int dist = Math.abs(arr[0] - target);


        for (int i = 1; i < arr.length; i++) {
            int cdist = Math.abs(arr[i] - target);
//TODO MAKE CLOSEST NUMBER BE ABOVE TARGET
            if (cdist < dist) {
                idx = i;
                dist = cdist;
            }
        }
        Log.e("FIND!!!", "CLOSEST MINUTE IS --->" + arr[idx]);
        int minute_of_day = arr[idx];

        return minute_of_day;

    }

Solution

  • Just fix the code according to your requirement: find the minimal number of those above the target. Also it would make sense to check for null values in the input array.

    public static Integer findClosestAbove(Integer[] arr, int target) {
        Integer min = null;
    
        for (Integer x : arr) {
            if (x != null && x > target && (min == null || min > x)) {
                min = x;
            }
        }
        return min; // may be null
    }
    

    Similar solution using Java Stream API is as follows:

    public static Integer findClosestAboveStream(Integer[] arr, int target) {
        return Arrays.stream(arr)
                     .filter(x -> x != null && x > target)
                     .min(Integer::compareTo) // Optional<Integer>
                     .orElse(null); // or orElseGet(() -> null)
    }
    

    Test:

    Integer[] arr = new Integer[]{1, 2, null, 7, 4};
    System.out.println("findClosest:\t" + findClosestAbove(arr, 5));
    System.out.println("findClosest2:\t" + findClosestAboveStream(arr, 5));
    

    Output:

    findClosest:    7
    findClosest2:   7