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]
.
这道题让我们在一个有序整数数组中寻找相同目标值的起始和结束位置,而且限定了时间复杂度为O(logn),这是典型的二分查找法的时间复杂度,所以这道题我们也需要用此方法,我们的思路是首先对原数组使用二分查找法,找出其中一个目标值的位置,然后向两边搜索找出起始和结束的位置,代码如下:
解法一
class Solution { public: vector<int> searchRange(int A[], int n, int target) { vector<int> res; int idx = searchRangeDFS(A, 0, n - 1, target); if (idx == -1) res.resize(2, -1); else { int left = idx; while (left > 0 && A[left - 1] == A[idx]) --left; int right = idx; while (right < n - 1 && A[right + 1] == A[idx]) ++right; res.push_back(left); res.push_back(right); } return res; } int searchRangeDFS(int A[], int left, int right, int target) { if (left > right) return -1; int mid = (left + right) / 2; if (A[mid] == target) return mid; if (A[mid] < target) return searchRangeDFS(A, mid + 1, right, target); else return searchRangeDFS(A, left, mid - 1, target); } };
可能有些人会觉得上面的算法不是严格意义上的O(logn)的算法,因为在最坏的情况下会变成O(n),比如当数组里的数全是目标值的话,从中间向两边找边界就会一直遍历完整个数组,那么我们下面来看一种真正意义上的O(logn)的算法,使用两次二分查找法,第一次找到左边界,第二次调用找到右边界即可,具体代码如下:
解法二
class Solution { public: vector<int> searchRange(int A[], int n, int target) { vector<int> res(2, -1); int start = 0, end = n - 1; while (start < end) { int mid = (start + end) / 2; if (A[mid] < target) start = mid + 1; else end = mid; } if (A[start] != target) return res; res[0] = start; end = n; while (start < end) { int mid = (start + end) / 2; if (A[mid] > target) end = mid; else start = mid + 1; } res[1] = start - 1; return res; } };