just modify the binary search code a little


  • 0
    2
    public int[] searchRange(int[] nums, int target) {
            int left = -1, right = -1;
            if(nums == null || nums.length == 0)
                return new int[]{-1, -1};
            int low = 0, high = nums.length - 1;
            while(low < high) {
                int mid = low + (high - low) / 2;//when high - low = 1, mid = low, to avoid unlimited recur let low = mid + 1;
                if(nums[mid] < target) 
                    low = mid + 1;
                else if(nums[mid] >= target) //target locate in (low, mid],let the high move to left
                    high = mid ;
            }
            if(low < nums.length && nums[low] == target)
                left = low;
            high = nums.length - 1;
            while(low < high) {
                int mid = high - (high - low) / 2; //when high - low = 1, mid = high, to avoid unlimited recur let hight = mid - 1 
                if(nums[mid] <= target) //target locate in [mid, high],let the low move to right
                    low = mid;
                else if(nums[mid] > target)
                    high = mid - 1;
            }
            if(low < nums.length && nums[low] == target)
                right = low;
            
            return new int[]{left, right};
            
        }
    

Log in to reply
 

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