Search for a Range

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].

Solution:

public class Solution {
    public int[] searchRange(int[] nums, int target) {
        int lo=0, hi=nums.length-1;
        int[] ans = new int[2];
        double t = target - 0.5;
        while(lo<=hi){
            int mid = lo + (hi-lo)/2;
            if(nums[mid]<t){
                lo = mid+1;
            } else { /* noted that nums[mid]==t is not possible */
                hi = mid-1;
            }
        }
        if(lo==nums.length || nums[lo]!=target){
            ans[0] = -1;
            ans[1] = -1;
            return ans;
        }
        ans[0] = lo;
        t = target + 0.5;
        lo=0; 
        hi=nums.length-1;
        while(lo<=hi){
            int mid = lo + (hi-lo)/2;
            if(nums[mid]<t){
                lo = mid+1;
            } else { /* noted that nums[mid]==t is not possible */
                hi = mid-1;
            }
        }
        ans[1] = hi;
        return ans;
    }
}
comments powered by Disqus