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); } };
http://fisherlei.blogspot.com/2013/01/leetcode-search-for-range.html
时间: 2024-10-09 16:05:50