统计一个数字在排序数组中出现的次数
//时间复杂度O(n)
public class Solution {
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;
}
}
//利用二分法,不断递归,找到k就+1,然后继续递归查找
public class Solution {
public int GetNumberOfK(int [] array , int k) {
if(array.length == 0 || k < array[0] || k > array[array.length-1])
return 0;
return getCount(array, k, 0, array.length-1);
}
public int getCount(int[] array, int k, int left, int right){
if (left > right)
return 0;
int mid = (right - left) / 2 + left;
if (k > array[mid])
return getCount(array, k, mid+1, right);
else if (k < array[mid])
return getCount(array, k, left, mid-1);
else {
return 1 + getCount(array, k, left, mid-1) + getCount(array, k, mid + 1, right);
}
}
}