解题思路1:
public class Solution {
public int GetNumberOfK(int [] array , int k) {
int count = 0;
int result = findIndex(array, 0, array.length-1, k);
if(result == -1)
{
return count;
}
//至少一个了
count+= 1;
//从中间向后查找
for(int i = result + 1; i <= array.length -1; i++){
if(array[i] != k){
break;
}
count++;
}
//从中间向前查找
for(int i = result - 1; i >= 0 ; i--){
if(array[i] != k){
break;
}
count++;
}
return count;
}
//寻找在array中k对应的下标
public int findIndex(int[] array, int firstIndex, int lastIndex,int k){
if(firstIndex > lastIndex){
return -1;
}
if(array[firstIndex] == k){
return firstIndex;
}
if(array[lastIndex] == k){
return lastIndex;
}
//求中间下标
int mid = (firstIndex + lastIndex)/2;
if(array[mid] == k){
return mid;
}else if(array[mid] > k){
return findIndex(array, mid + 1, lastIndex, k);
}else if(array[mid] < k){
return findIndex(array,firstIndex, mid - 1, k);
}
return -1;
}
}