# 剑指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

posted @ 2017-10-12 15:25  AI菌  阅读(97)  评论(0编辑  收藏