Home >Backend Development >PHP Tutorial >How to count the number of times a number appears in a sorted array in PHP (code)

How to count the number of times a number appears in a sorted array in PHP (code)

不言
不言forward
2018-10-08 15:24:222589browse

The content of this article is about how PHP can count the number of times a number appears in a sorted array (code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.

Count the number of times a number appears in the sorted array.
1. Ordered array search, use binary method
2. Binary method to find the position of the first occurrence, binary method to find the position of the last occurrence, end - start 1

left=getLeft(data,k)
right=getRight(data,k)
retun right-left+1
getLeft data,k
    left=0
    right=arr.length-1
    mid=left+(right-left)/2
    while  left<=right
        if arr[mid]<k    //关键
            left=mid+1
        else
            right=mid-1
        mid=left+(right-left)/2
    return left
getRight data,k
    left=0
    right=arr.length-1
    mid=left+(right-left)/2
    while  left<=right
        if arr[mid]<=k   //关键
            left=mid+1
        else
            right=mid-1
        mid=left+(right-left)/2
    return right
<?php
function GetNumberOfK($data, $k) 
{
        $left=getLeft($data,$k);
        $right=getRight($data,$k);
        return $right-$left+1;
}
function getLeft($arr,$k){
        $left=0;
        $right=count($arr)-1;
        $mid=intval($left+($right-$left)/2);
        while($left<=$right){
                if($arr[$mid]>=$k){//关键
                        $right=$mid-1;
                }else{
                        $left=$mid+1;
                }   
                $mid=intval($left+($right-$left)/2);
        }   
        return $left;
}
function getRight($arr,$k){
        $left=0;
        $right=count($arr)-1;
        $mid=intval($left+($right-$left)/2);
        while($left<=$right){
                if($arr[$mid]<=$k){//关键
                        $left=$mid+1;
                }else{
                        $right=$mid-1;
                }   
                $mid=intval($left+($right-$left)/2);
        }   
        return $right;
}
$arr=array(1,2,3,4,4,4,5);
$m=GetNumberOfK($arr,4);
var_dump($m);

The above is the detailed content of How to count the number of times a number appears in a sorted array in PHP (code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete