剑指 Offer 53 - I. 在排序数组中查找数字 I
题目链接
思路分析
利用二分查找即可。
class Solution {
public:
int search(vector<int>& nums, int target) {
std::ios::sync_with_stdio(false);
if(nums.empty()) return 0;
int l = 0, r = nums.size() - 1;
while(l < r){
int mid = (l + r) / 2;
if(nums[mid] >= target) r = mid;
else l = mid + 1;
}
if(nums[l] != target) return {0};
else{
int res = l;
l = 0, r = nums.size() - 1;
while(l < r){
int mid = (l + r + 1) / 2;
if(nums[mid] <= target) l = mid;
else r = mid - 1;
}
return l - res + 1;
}
}
};