37 lines
793 B
Java
37 lines
793 B
Java
|
# 53. 数字在排序数组中出现的次数
|
||
|
|
||
|
[NowCoder](https://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2?tpId=13&tqId=11190&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
|
||
|
|
||
|
## 题目描述
|
||
|
|
||
|
```html
|
||
|
Input:
|
||
|
nums = 1, 2, 3, 3, 3, 3, 4, 6
|
||
|
K = 3
|
||
|
|
||
|
Output:
|
||
|
4
|
||
|
```
|
||
|
|
||
|
## 解题思路
|
||
|
|
||
|
```java
|
||
|
public int GetNumberOfK(int[] nums, int K) {
|
||
|
int first = binarySearch(nums, K);
|
||
|
int last = binarySearch(nums, K + 1);
|
||
|
return (first == nums.length || nums[first] != K) ? 0 : last - first;
|
||
|
}
|
||
|
|
||
|
private int binarySearch(int[] nums, int K) {
|
||
|
int l = 0, h = nums.length;
|
||
|
while (l < h) {
|
||
|
int m = l + (h - l) / 2;
|
||
|
if (nums[m] >= K)
|
||
|
h = m;
|
||
|
else
|
||
|
l = m + 1;
|
||
|
}
|
||
|
return l;
|
||
|
}
|
||
|
```
|