Clean binary search java solution


  • 0
    S
    	public int[] searchRange(int[] nums, int target) {
    		int lo=0;
    		int hi=nums.length-1;
    		int[] res=new int[]{-1,-1};
    
    		while(lo<=hi){
    			int mid=lo+(hi-lo)/2;
    			//target range lies in the right half
    			if(nums[mid]<target) lo=mid+1;
    			//target range lies in the left half
    			else if(nums[mid]>target) hi=mid-1;
    			//expand from mid to get the range
    			else{
    				int left=mid;
    				int right=mid;
    				res[0]=left;res[1]=right;
    				//find the left boundary
    				while(left>lo&&nums[left-1]==nums[left]){
    					left--;
    					res[0]=left;
    				}
    				//find the right boundary
    				while(right<hi&&nums[right+1]==nums[right]){
    					right++;
    					res[1]=right;
    				}
    				return res;
    			}
    		}
    		return res;
    	}
    
    

Log in to reply
 

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