題目鏈接
tag:
- Medium;
- Binary Search;
question
??Given an array of integers nums 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].
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
思路:
??這道題讓我們在一個有序整數(shù)數(shù)組中尋找相同目標(biāo)值的起始和結(jié)束位置,而且限定了時間復(fù)雜度為O(logn)呛谜,這是典型的二分查找法的時間復(fù)雜度,所以這道題我們也需要用此方法,我們的思路是首先對原數(shù)組使用二分查找法沸版,找出其中一個目標(biāo)值的位置近忙,然后向兩邊搜索找出起始和結(jié)束的位置湘纵,代碼如下:
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int index = search(nums, 0, nums.size()-1, target);
if (index == -1) return {-1, -1};
int left = index, right = index;
while (left > 0 && nums[left-1] == nums[index]) --left;
while (right < nums.size()-1 && nums[right+1] == nums[index]) ++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);
}
};