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)

不言
Release: 2023-04-04 08:54:02
forward
2585 people have browsed it

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
Copy after login
<?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);
Copy after login

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!

Related labels:
php
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template