PHP realizes the method of counting the occurrence times of a number in the sorting array

  • 2021-09-04 23:38:57
  • OfStack

In this paper, an example is given to describe the method of counting the number of occurrences of a number in the sorting array by PHP. Share it for your reference, as follows:

Title

Counts the number of times a number appears in the sort array.

Problem solution

Since it is a sorted array, it is most efficient to use 2-point lookup. After finding it, expand it to both sides for 1 time.

Code


<?php
function GetNumberOfK($data, $k)
{
  if(count($data)==0){
    return 0;
  }
  $index = 0;
  $low = 0;
  $high = count($data)-1;
  $middle = 0;
  //2 Find by sub-search k Adj. 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 you don't find it 
  if($index==-1){
    return 0;
  }
  // Found it   Look for boundaries left and right respectively 
  $start = $index;
  $end = $index;
  $count = 0;
  while($data[$start]==$k){
    $count++;
    $start--;
  }
  while($data[$end]==$k){
    $count++;
    $end++;
  }
  return $count-1;
}

PS: Here, we recommend two statistical tools with similar functions (JS implementation) for your reference:

Online word count tool:
http://tools.ofstack.com/code/zishutongji

Online Character Statistics and Editing Tools:
http://tools.ofstack.com/code/char_tongji

For more readers interested in PHP related content, please check the topics of this site: "PHP Data Structure and Algorithm Tutorial", "PHP Array (Array) Operation Skills Encyclopedia", "php String (string) Usage Summary" and "php Programming Algorithm Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: