34. Search for a Range
Posted Zzz...y
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了34. Search for a Range相关的知识,希望对你有一定的参考价值。
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]
.
Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4] Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1]
找目标值涵盖的区间,要求时间复杂度O(logn)。
看到O(logn),直接想到的就是二分查找。然后想到用两次二分法,分别求第一个下界和上界。
1 class Solution { 2 public: 3 vector<int> searchRange(vector<int>& nums, int target) { 4 if (nums.empty()) 5 return {-1, -1}; 6 int l = -1; 7 int r = nums.size(); 8 int mid, low, high; 9 while (l < r - 1) { 10 mid = l + (r - l) / 2; 11 if (nums[mid] >= target) 12 r = mid; 13 else 14 l = mid; 15 } 16 low = (r == nums.size() || nums[r] < target)? r: r-1; 17 l = -1; 18 r = nums.size(); 19 while (l < r - 1) { 20 mid = l + (r - l) / 2; 21 if (nums[mid] <= target) 22 l = mid; 23 else 24 r = mid; 25 } 26 high = (l == -1 || nums[l] > target)? l: l+1; 27 if (high - low > 1) { 28 return {low+1, high-1}; 29 } 30 return {-1, -1}; 31 } 32 };
以上是关于34. Search for a Range的主要内容,如果未能解决你的问题,请参考以下文章