A 1ms solution by java with annotation


  • -1
    S
    public int[] searchRange(int[] nums, int target) {
            int start=0;
            int end = nums.length;
            int mid = 0;
            while(start<end){
            	mid = start+(end-start)/2;
            	if(nums[mid]>target)
            		end = mid;
            	else if(nums[mid]<target)
            		start = mid+1;
            	else
            		break;
            }
            //the target is not found,return [-1,-1]
            if(start>=end){
            	int[] result ={-1,-1};
            	return result;
            }
            int left=mid;
        	int right=mid;
        	//expand the range in two direction.
            while(true){
            	int tmpl = left;
            	int tmpr = right;
            	if(left>=0){
            		if(nums[left]==target)
            			left--;
            		}
            	if(right<nums.length){
            		if(nums[right]==target)
            			right++;
            	}
            	if(left==tmpl&&right==tmpr){
            		left++;
            		right--;
            		break;	
            	}
            }
    		int[] result={left,right};
    		return result;
    	}

Log in to reply
 

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