Count the number of times a number appears in the sorted array.
Example 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
Example 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
limit:
0 <= array length <= 50000
Note: This question is the same as question 34 on the main site (only the return value is different): https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
Problem-solving ideas
Find the position where the target appears in nums
Assuming that the existence boundary is left and right, satisfying nums[left] <target && nums[right]> target,
we need to find
the window size corresponding to the largest left and smallest right that meets the condition is right-left-1;
specific implementation:
Use the dichotomy to find the left and right boundaries twice.
Optimization: Simplify the code, in fact, you can use the left boundary, and the boundary solution is changed to the left boundary solution of target+1, and the corresponding window becomes right-left (no need 1)
class Solution {
private:
// 找到>=target的左边界,就是满足 nums[i] >= target里的i的最小值
inline int BinaryLeft(vector<int>& nums, int target)
{
int l = 0;
int r = nums.size() -1 ;
int m = 0;
while (l <= r)
{
m = (l+r) >> 1;
if (nums[m] < target)
{
l = m + 1;
}
else//nums[m] >= target
{
r = m - 1;
}
}
// cout << target << " " << l << endl;
return l;
}
public:
int search(vector<int>& nums, int target) {
// 题目假设存在target,无法额外判断
// 二分查找都是left边界,等于是前开后闭,这里计算窗口无需额外减1
return BinaryLeft(nums, target+1) - BinaryLeft(nums, target);
}
};
The logic implemented by the code:
Take nums = [5,7,7,8,8,10], target = 8 as an example:
1-、m=2,nums[m] <target,L=3;
2-、m=4;nums[ 4] >=8, R=3 and
finally return to L3.
Take nums = [5,7,7,8,8,10], target = 9 as an example:
1-, m=2, nums[2] <9, L=3;
2-, m=4; nums[4] <9,L=5
3, m=5,nums[5]>=9,R=4
returns LThe
final value of 5 is: 5-3=2