# 剑指offer三十七之数字在排序数组中出现的次数

统计一个数字在排序数组中出现的次数。

``` public int GetNumberOfK(int[] array, int k) {
int count = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == k) {
count++;
}
}
return count;
}```

View Code

```public class Solution2 {
public int GetNumberOfK(int[] array, int k) {

int lower = getLower(array, k);
int upper = getUpper(array, k);
return upper - lower + 1;
}

//获取k第一次出现的下标

public  int getLower(int[] array, int k) {
int start = 0, end = array.length - 1;
int mid = (start + end) / 2;

while (start <= end) {
if (array[mid] < k) {
start = mid + 1;
} else {
end = mid - 1;
}
mid = (start + end) / 2;
}
return start;
}

//获取k最后一次出现的下标
int getUpper(int[] array, int k) {
int start = 0, end = array.length - 1;
int mid = (start + end) / 2;

while (start <= end) {
if (array[mid] <= k) {
start = mid + 1;
} else {
end = mid - 1;
}
mid = (start + end) / 2;
}

return end;
}
}```

View Code

———————————————

https://www.nowcoder.com/questionTerminal/70610bf967994b22bb1c26f9ae901fa2

原文作者：hezhiyao
原文地址: https://www.cnblogs.com/hezhiyao/p/7656288.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。