9ms Java binary search


  • 0
    public int[] searchRange(int[] nums, int target) {
            int start = 0;
            int end = nums.length - 1;
            int[] coordinate = {-1, -1};
            while (start <= end) {
                int middle = (start + end) / 2;
                int middleValue = nums[middle];
                if (target == middleValue) {
                    coordinate[0] = middle;
                    coordinate[1] = middle;
                    for (int i = middle - 1; i >= 0; i--) {
                        if (target == nums[i]) {
                            coordinate[0] = i;
                        } else {
                            break;
                        }
                    }
                    for (int i = middle + 1; i <= end; i++) {
                        if (target == nums[i]) {
                            coordinate[1] = i;
                        } else {
                            break;
                        }
                    }
                    return coordinate;
                } else if (target < middleValue) {
                    end = middle - 1;
                } else {
                    start = middle + 1;
                }
            }
            return coordinate;
        }
    

  • 0
    C

    I think the premise of this algorithm is all target numbers stay together


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.