JAVA-------------------Easy Version To Understand!!!!!!!!!!


  • -1
    H
    public static int BinarySearch(int[] a, int low, int high, int target) {
    	int mid;
    	while (low <= high) {
    		mid = low + (high - low) / 2;
    		if (a[mid] > target)
    			high = mid - 1;
    		else if (a[mid] < target)
    			low = mid + 1;
    		else
    			return mid;
    	}
    	return -1;
    }
    
    public static int[] searchRange(int[] nums, int target) {
    	if (nums == null || nums.length == 0)
    		return new int[0];
    	int[] result = new int[2];
    	int low = 0, high = nums.length - 1;
    	int position = BinarySearch(nums, low, high, target), tmp = position;
    	if (position == -1) {
    		result[0] = -1;
    		result[1] = -1;
    		return result;
    	}
    	if (position == 0 || nums[position] > nums[position - 1])
    		result[0] = position;
    	else {
    		while (position > 0 && nums[position] == nums[position - 1])
    			position = BinarySearch(nums, 0, position - 1, target);
    		result[0] = position;
    	}
    
    	position = tmp;
    	if (position == nums.length - 1 || nums[position] < nums[position + 1])
    		result[1] = position;
    	else {
    		while (position < nums.length - 1 && nums[position] == nums[position + 1])
    			position = BinarySearch(nums, position + 1, nums.length - 1, target);
    		result[1] = position;
    	}
    
    	return result;
    }

Log in to reply
 

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