function GetNumberOfK(data,k)
{
var position1=binarySearch(data,k);
var position2=binarySearch(data,k+1);
return position2-position1;
}
function binarySearch(data,k){
var left=0,right=data.length;
while(left<right){
var mid=Math.floor((right-left)/2)+left;
if(data[mid]>=k) right=mid;
else left=mid+1;
}
return left;
}
普通方法:
function GetNumberOfK(data,k)
{
var start=data.indexOf(k);
if(start===-1) return 0;
var count=0;
for(var i=start;i<data.length;i++){
if(data[i]===k) count++;
else{
break;
}
}
return count;
}