題目
Given an array of integers sorted in ascending order, 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].
解題之法
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int idx = search(nums, 0, nums.size() - 1, target);
if (idx == -1) return {-1, -1};
int left = idx, right = idx;
while (left > 0 && nums[left - 1] == nums[idx]) --left;
while (right < nums.size() - 1 && nums[right + 1] == nums[idx]) ++right;
return {left, right};
}
int search(vector<int>& nums, int left, int right, int target) {
if (left > right) return -1;
int mid = left + (right - left) / 2;
if (nums[mid] == target) return mid;
else if (nums[mid] < target) return search(nums, mid + 1, right, target);
else return search(nums, left, mid - 1, target);
}
};
分析
這道題讓我們?cè)谝粋€(gè)有序整數(shù)數(shù)組中尋找相同目標(biāo)值的起始和結(jié)束位置汪榔,而且限定了時(shí)間復(fù)雜度為O(logn)馍资,這是典型的二分查找法的時(shí)間復(fù)雜度厦取,所以這道題我們也需要用此方法。
首先對(duì)原數(shù)組使用二分查找法,找出其中一個(gè)目標(biāo)值的位置躺盛,然后向兩邊搜索找出起始和結(jié)束的位置