Easy to understand recursive O(log(n)) solution


  • 0
    S
    public class Solution {
        public int min = -1;
        public int max = -1;
        public int[] searchRange(int[] nums, int target) {
            searchRange(nums,target,0,nums.length-1);
            int[] res = {min,max};
            return res;
        }
        
        public void searchRange(int[] nums, int target, int i , int j){
            if(i<=j){
                int k = (i+j)/2;
                if(nums[k]==target){
                    if(k < min || min == -1){
                        min = k;
                    }
                    if(k > max || max == -1){
                        max = k;
                    }
                    searchRange(nums,target,i,k-1);
                    searchRange(nums,target,k+1,j);
                }
                if(nums[k] < target) searchRange(nums,target,k+1,j);
                if(nums[k] > target) searchRange(nums,target,i,k-1);
            }
        }
    }
    

Log in to reply
 

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