本文實例講述了PHP實現統計一個數字在排序數組中出現次數的方法。分享給大家供大家參考,具體如下:
題目
統計一個數字在排序數組中出現的次數。
題解
既然是排序數組,使用二分查找是效率最高的。找到之后再向兩側拓展一下。
代碼
?php
function GetNumberOfK($data, $k)
{
if(count($data)==0){
return 0;
}
$index = 0;
$low = 0;
$high = count($data)-1;
$middle = 0;
//二分查找找到k的index
while($low=$high){
$middle = ($high+$low)>>1;
if($data[$middle]==$k){
$index = $middle;
break;
}
else if($data[$middle]>$k) {
$high = $middle -1;
}else{
$low = $middle+1;
}
$index = -1;
}
// console.log(index);
// 如果沒找到
if($index==-1){
return 0;
}
//找到了 分別往左右查找邊界
$start = $index;
$end = $index;
$count = 0;
while($data[$start]==$k){
$count++;
$start--;
}
while($data[$end]==$k){
$count++;
$end++;
}
return $count-1;
}
PS:這里再為大家推薦2款功能類似的統計工具(JS實現)供大家參考使用:
在線字數統計工具:
http://tools.jb51.net/code/zishutongji
在線字符統計與編輯工具:
http://tools.jb51.net/code/char_tongji
更多關于PHP相關內容感興趣的讀者可查看本站專題:《PHP數據結構與算法教程》、《PHP數組(Array)操作技巧大全》、《php字符串(string)用法總結》及《php程序設計算法總結》
希望本文所述對大家PHP程序設計有所幫助。
您可能感興趣的文章:- php實現數組中出現次數超過一半的數字的統計方法
- PHP重置數組為連續數字索引的幾種方式總結
- PHP簡單實現合并2個數字鍵數組值的方法
- php恢復數組的key為數字序列的方法
- php提取數字拼接數組的具體操作