Leetcode–Search for a Range

The Problem:

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm’s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

Notes:

  1. Do binary search, when found match, then expand to get range.
  2. Mistake I made:
    1. When doing low– and high++, need to check the bound before accessing the element.
    2. Array to initialize with value can written as ” new int[] {a, b}”

Java Solution

public class Solution {
    public int[] searchRange(int[] A, int target) {
        if(A.length==0 || target < A[0] || target > A[A.length-1]) 
           return new int[]{-1,-1};
        int low = 0;
        int high = A.length-1;
        while(low <= high){
            int mid = (low+high)/2;
            if(A[mid]== target){
                low = mid-1;
                while(low >=0 && A[low]==target){
                    low--;
                }
                high = mid+1;
                while(high < A.length && A[high]==target){
                    high++;
                }
                return new int[]{low+1, high-1};
            }
            else if (A[mid] < target){
                low = mid+1;
            }
            else {
                high = mid-1;
            }
        }
        return new int[]{-1,-1};
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s