8ms Simple Java Solution


  • 0
    O
    public int[] searchRange(int[] nums, int target) {
    		int start = -1, end = -1;
    		int l = 0, r = nums.length - 1;
    
    		int maxstart = r;
    		while (maxstart >= 0 && 
                        ( maxstart =
                               this.findStartPos(nums, target, 0, maxstart)) != -1) {
    			start = maxstart;
    			--maxstart;
    		}
    
    		if (start != -1) {
    			int fromR = start;
    			while (
                                    fromR <= r  && 
                                   ( fromR = this.findStartPos(nums, target, fromR, r)) != -1 ) {
    				end = fromR; 
    				++fromR;
    			}
    		}
    
    		return new int[] { start, end };
    	}
    
    	private int findStartPos(int[] nums, int v, int l, int r) {
    
    		while (l <= r) {
    			int m = l + (r - l) / 2;
    			if (v < nums[m])
    				r = m - 1;
    			else if (v > nums[m])
    				l = m + 1;
    			else {
    				return m;
    			}
    		}
    		return -1;
    	}
    

Log in to reply
 

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