Java 2-binary search solution with inline explanations, easy to understand


  • 0
    R
    public int[] searchRange(int[] nums, int target) {
        int len = nums.length;
        
        // Search for start index
        int beginIndex = -1;
        int start = 0;
        int end = len - 1;
    
        while (start < end) {
            int mid = start + (end - start) / 2;
            if (nums[mid] >= target) { // When nums[mid] == target, search towards the left
                end = mid;
            } else {
                start = mid + 1;
            }
        }
        
        // Take care the single item case, making the search for end easier
        if (len == 1) {
            return nums[0] == target? new int[] {0, 0} : new int[] {-1, -1};
        }
        
        // If target exist, start will be the starting point
        if (nums[start] == target) {
            beginIndex = start;
        } else {
            return new int[] {-1, -1};
        }
        
        // Search for end index
        int endIndex = -1;
        start = 0;
        end = len - 1;
    
        while (start < end) {
            int mid = start + (end - start) / 2;
            if (nums[mid] > target) { // When nums[mid] == target, search towards the right
                end = mid;
            } else {
                start = mid + 1;
            }
        }
        
        // If the target is all the way to the end of nums[], then the start/end should be pointing to the end of nums[], thus start/end/len - 1 should be the end index;
        // otherwise, nums[start] should be the first value that's larger than target, therefore (start - 1) should be the end index of target.
        endIndex = nums[start] == target? start : start - 1;
        return new int[] {beginIndex, endIndex};
    }

Log in to reply
 

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