首页 > 代码库 > LeetCode 34 Search for a Range

LeetCode 34 Search for a Range

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm‘s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

思路;使用折半查找,首先看能不能找到target这个值,若不能则返回[-1,-1],若能,则再递归的查找左边界和右边界。
public class Solution {
	public int[] searchRange(int[] A, int target) {
		int[] result = new int[] { -1, -1 };
		int left = 0;
		int right = A.length - 1;
		int middle;

		while (left <= right) {
			middle = (left + right) / 2;
			if (A[middle] > target) {
				right = middle - 1;
			} else if (A[middle] < target) {
				left = middle + 1;
			} else {
				result[0] = searchLeft(A, left, middle, target);
				result[1] = searchRight(A, middle, right, target);
				return result;
			}
		}
		return result;
	}

	private int searchLeft(int[] A, int begin, int end, int target) {
		int left = begin;
		int right = end;
		int middle;

		while (left < right) {
			middle = (left + right) / 2;
			//搜索左边界的前提是数组中已经存在target,
			//并且参数传递经来的是数组值不大于target的部分
			//故不需要检查A[middle]是否比target大
			//只需要比较A[middle]是否比target小或者相等
			if (A[middle] < target) {
				left = middle + 1;
			} else {
				return searchLeft(A, left, middle, target);
			}
		}
		return left;
	}

	private int searchRight(int[] A, int begin, int end, int target) {
		int left = begin;
		int right = end;
		int middle ;

		while (left < right) {
			middle = (left + right) / 2;
			//搜索右边界的前提是数组中已经存在target,
			//并且参数传递经来的是数组值不小于target的部分
			//故不需要检查A[middle]是否比target小
			//只需要比较A[middle]是否比target大或者相等
			if (A[middle] > target) {
				right = middle - 1;
			} else {
				//注意这比searchLeft多的一部分,
				//为了防止 A={8,9},target=8或者 A={8,8},target=8这一类情况
				if (middle == left && A[right] > target)
					return left;
				if (middle == left && A[right] == target)
					return right;
				return searchRight(A, middle, right, target);
			}
		}
		return left;
	}
}


LeetCode 34 Search for a Range