LeetCode | 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].

分析

同樣是二分查找,先找左邊界,如果沒找到,返回[-1, -1],如果找到了,再找右邊界。

代碼

public class SearchForARange {
	public int[] searchRange(int[] A, int target) {
		if (A == null || A.length == 0) {
			return new int[] { -1, -1 };
		}
		int low = 0;
		int high = A.length - 1;
		while (low <= high) {
			int mid = low + (high - low) / 2;
			if (A[mid] >= target) {
				high = mid - 1;
			} else {
				low = mid + 1;
			}
		}
		int left = (low < A.length && A[low] == target) ? low : -1;
		if (left == -1) {
			return new int[] { -1, -1 };
		}

		low = 0;
		high = A.length - 1;
		while (low <= high) {
			int mid = low + (high - low) / 2;
			if (A[mid] <= target) {
				low = mid + 1;
			} else {
				high = mid - 1;
			}
		}
		return new int[] { left, high };
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章