# [剑指offer] 数字在排序数组中出现的次数

#### 参考代码

```public class Solution {
public int GetNumberOfK(int [] array , int k) {
int len = array.length;
if(len == 0)
return 0;
int first = getFirst(array, k, 0, len-1);
int last = getLast(array, k, 0, len-1);
if(first != -1 && last != -1){
return last - first + 1;
}
return 0;
}

public int getFirst(int [] array, int k, int start, int end){
int mid;
while(start <= end){
mid = start + (end - start) / 2;
if(k <= array[mid])
end = mid - 1;
else
start = mid + 1;
}
if(start < array.length && array[start] == k)
return start;
else
return -1;
}
// 循环
public int getLast(int [] array, int k, int start, int end){
int mid;
while(start <= end){
mid = start + (end - start) / 2;
if(k >= array[mid])
start = mid + 1;
else
end = mid - 1;
}
if(end >= 0 && array[end] == k)
return end;
else
return -1;
}
}```

```public class Solution {
public int GetNumberOfK(int [] array , int k) {
return biSearch(array, k+0.5) - biSearch(array, k-0.5);
}
public int biSearch(int [] array, double k){
int start  = 0, end = array.length - 1;
while(start <= end){
int mid = start + (end - start)/2;
if(array[mid] > k){
end = mid - 1;
}else{
start = mid + 1;
}
}
return start;
}
}```

110 篇文章26 人订阅

0 条评论

## 相关文章

Given two binary strings, return their sum (also a binary string). For example, ...

2858

1002

### Leetcode 224. Basic Calculator

Implement a basic calculator to evaluate a simple expression string. The expre...

2377

上篇文章我们介绍了ArrayList类的基本的使用及其内部的一些方法的实现原理，但是这种集合类型虽然可以随机访问数据，但是如果需要删除中间的元素就...

2025

933

1.4K2

823

32212

782