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]
.
思路:
二分搜索。可以参见 C++的 upper_bound和lower_bound的实现。
题解:
class Solution { public: int lbound (int* A, int n, int target) { if (n == 0 || A == 0) return -1; int lower = 0; int upper = n - 1; while (lower < upper) { int mid = (lower + upper) / 2; if (A[mid] >= target) upper = mid; else if (A[mid] < target) lower = mid + 1; } if (A[lower] != target) return -1; return lower; } int ubound (int* A, int n, int target) { if (n == 0 || A == 0) return -1; int lower = 0; int upper = n - 1; while (lower < upper) { int mid = (lower + upper + 1) / 2; if (A[mid] > target) upper = mid - 1; else if (A[mid] <= target) lower = mid; } if (A[upper] != target) return -1; return upper; } vector<int> searchRange(int A[], int n, int target) { return vector<int>({{lbound(A, n, target), ubound(A, n, target)}}); } };