2019-11-02 12:07:41 +08:00
|
|
|
# 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;
|
|
|
|
}
|
|
|
|
```
|
2019-11-02 14:39:13 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2019-11-02 17:33:10 +08:00
|
|
|
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>
|