Find the first element in a sorted array that is greater than the target

后端 未结 8 569
青春惊慌失措
青春惊慌失措 2020-11-30 17:40

In a general binary search, we are looking for a value which appears in the array. Sometimes, however, we need to find the first element which is either greater or less than

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 18:15

    public static int search(int target, int[] arr) {
            if (arr == null || arr.length == 0)
                return -1;
            int lower = 0, higher = arr.length - 1, last = -1;
            while (lower <= higher) {
                int mid = lower + (higher - lower) / 2;
                if (target == arr[mid]) {
                    last = mid;
                    lower = mid + 1;
                } else if (target < arr[mid]) {
                    higher = mid - 1;
                } else {
                    lower = mid + 1;
           }
        }
        return (last > -1 && last < arr.length - 1) ? last + 1 : -1;
    }
    

    If we find 'target == arr[mid]', then any previous element would be either less than or equal to target. Hence, lower boundary is set as 'lower=mid+1'. Also, 'last' is the last index of 'target'. Finally we return 'last+1' - taking care of boundary conditions.

提交回复
热议问题