Java solution O(logn)


  • 0
    V
    public class Solution {
        public int[] searchRange(int[] nums, int target) {
            if(nums.length == 0 || nums == null)return new int[]{-1,-1};
            int left = 0;
            int right = nums.length;
            int mid;
            while(left<right){
                mid = left + (right-left)/2;
                if(nums[mid] == target){
                    left = mid;
                    right = mid;
                    while(left>=0 && nums[left] == target){
                        left--;
                    }
                    while(right< nums.length && nums[right]==target){
                        right++;
                    }
                    return new int[]{left+1,right-1};
                }
                if(nums[mid]>target){
                    right = mid;
                    continue;
                }
                if(nums[mid]<target){
                    //System.out.println(mid);
                    left = mid + 1;
                    continue;
                }
            }
            return new int[]{-1,-1};
        }
    }
    

Log in to reply
 

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