统计一个数字在排序数组中出现的次数。
题解
有序数组查找 基本都是二分
题目就是找数的下边界和上边界
写了两个二分 一个找上边界 一个找下边界
class Solution {
public:
int bin_search_right(int left, int right, vector<int> nums, int target) {
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] == target) {
if (mid + 1 <= nums.size()-1) {
if (nums[mid+1] > target) return mid;
else left = mid + 1;
} else {
return mid;
}
}
else if (nums[mid] < target) left = mid+1;
else right = mid - 1;
}
return -1;
}
int bin_search_left(int left, int right, vector<int> nums, int target) {
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] == target) {
if (mid - 1 >= 0) {
if (nums[mid-1] < target) return mid;
else right = mid - 1;
} else return mid;
} else if (nums[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
int search(vector<int>& nums, int target) {
int n = nums.size();
if (n == 0) return 0;
int right = bin_search_right(0, n-1, nums, target);
if(right < 0) return 0;
int left = bin_search_left(0, n-1, nums, target);
return right - left + 1;
}
};