题目:统计一个数字在排序数组中出现的次数。
思路:这个题目的提示点在 排序数组 这几个字上。找到就定义两个索引向两边统计;找不到就返回0。
public static int GetNumberOfK(int [] array , int k) {
int low = 0;
int high = array.length;
int mid = 0;
while(low<high) {
mid = (low+high)/2;
if(array[mid]==k) {
break;
}
else if(array[mid]>k) {
high = mid-1;
}
else
low = mid+1;
}
System.out.println(low+" "+high);
if(low>=high)
return 0;
int sum = 1;
low = mid-1;
high = mid+1;
while(high<array.length) {
if(array[high]==k)
sum++;
else
break;
high++;
}
while(low>-1) {
if(array[low]==k)
sum++;
else
break;
low--;
}
return sum;
}
PS:想问下大佬 直接用下面Python做算对吗?