题目描述
统计一个数字在升序数组中出现的次数。
示例1
输入
[1,2,3,3,3,3,4,5],3
返回值
4
想法自然是二分查找,代码如下:
/**
* [],3
* 4
*/
public int GetNumberOfK(int[] array, int k) throws Exception {
try{
int binarysearchIndex = binarysearch(array, k);
int num = 1;
int middle = binarysearchIndex;
while ((--middle >= 0) && array[middle] == k) {
num++;
}
while ((++binarysearchIndex <= (array.length - 1)) && array[binarysearchIndex] == k) {
num++;
}
return num;
}catch (Exception e){
}
return 0;
}
/**
* 二分查找找位置
*/
public int binarysearch(int[] array, int k) throws Exception {
if (k < array[0] || k > array[array.length - 1]) {
throw new Exception("error");
}
int start = 0;
int end = array.length - 1;
int middle = 0;
while (true) {
middle = (start + end) / 2;
if (k == array[middle]) {
break;
}
if (start == end) {
throw new Exception("error");
}
if ((end - start) == 1) {
// 直接判断
if (array[start] == k) {
return start;
} else if (array[end] == k) {
return end;
} else {
throw new Exception("error");
}
}
if (array[middle] > k) {
end = middle;
} else {
start = middle;
}
}
return middle;
}
测试代码:
public static void main(String[] args) {
Solution solution = new Solution();
int[] arrays = {1, 1, 1, 1, 1,2};
int binarysearch = 99;
try {
binarysearch = solution.GetNumberOfK(arrays, 3);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(binarysearch);
}