How about this solution?


  • 0
    J

    public class Solution {

    public int[] searchRange(int[] A, int target) {
        int length = A.length;
    	int mid = (length-1)/2;
    	int leftBound = 0;
    	int rightBound =length-1;
    	int left = -1;
    	int right = -1;
    	while(true){
    		if(A[mid] == target){
    			left = right = mid;
    			while(A[left] == target){
    				left--;
    				if(left < 0){
    					break;
    				}
    			}
    			while(A[right] == target){
    				right++;
    				if(right >= length){
    					break;
    				}
    			}
    			left++;
    			right--;
    			break;
    		}else if(A[mid] < target){
    			leftBound = mid+1;
    			if(leftBound >= length){
    				break;
    			}
    		}else{
    			rightBound = mid-1;
    			if(rightBound <0){
    				break;
    			}
    		}
    	    if(rightBound<leftBound){
    	        break;
    	    }
    		mid = (leftBound+rightBound)/2;
    	}
    	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.