2023-01-13 315
题目
统计一个数字在排序数组中出现的次数。
题解
既然是排序数组,使用二分查找是效率最高的。找到之后再向两侧拓展一下。
代码
<?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;
}
原文链接:https://77isp.com/post/25285.html
=========================================
https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。
数据库技术 2022-03-28
网站技术 2022-11-26
网站技术 2023-01-07
网站技术 2022-11-17
Windows相关 2022-02-23
网站技术 2023-01-14
Windows相关 2022-02-16
Windows相关 2022-02-16
Linux相关 2022-02-27
数据库技术 2022-02-20
抠敌 2023年10月23日
嚼餐 2023年10月23日
男忌 2023年10月22日
瓮仆 2023年10月22日
簿偌 2023年10月22日
扫码二维码
获取最新动态