美文网首页
求数组中某个元素连续出现的最大个数

求数组中某个元素连续出现的最大个数

作者: 幻无虚生 | 来源:发表于2019-05-29 09:55 被阅读0次

    随机一个a,b值的数组,数组长度len=100, 求最大连续b的个数。

    示例 :

    len=6 随机数组: [b,b,a,b,b,b]
    输出: 3

    function index(){
        $a='a';
        $b='b';
        $len=100;
        //$array=create_array($a,$b,$len);
        //echo json_encode($array).'<hr>';
        //$p=max_count($array);
        $c=max_count(["b","a","b","b","a","a","b","b","a","b","a","b","b","a","a","b","b","a","a","a","a","b","b","a","a","b","a","b","b","b","b","a","b","a","a","b","a","b","b","a","b","b","b","b","a","a","b","a","a","b","b","a","a","b","a","b","b","a","b","b","a","b","b","b","b","b","b","a","a","b","a","a","a","b","b","b","a","b","a","b","b","a","b","b","a","b","a","b","a","b","b","b","a","b","b","a","b","a","a","a"]);
        print_r($c);
        echo"<br>";
        $p=max_count_b($b,["b","a","b","b","a","a","b","b","a","b","a","b","b","a","a","b","b","a","a","a","a","b","b","a","a","b","a","b","b","b","b","a","b","a","a","b","a","b","b","a","b","b","b","b","a","a","b","a","a","b","b","a","a","b","a","b","b","a","b","b","a","b","b","b","b","b","b","a","a","b","a","a","a","b","b","b","a","b","a","b","b","a","b","b","a","b","a","b","a","b","b","b","a","b","b","a","b","a","a","a"]);
        print_r($p);
    
    }
    //生成随机数组
    function create_array($a,$b,$len){
        $array=[];
        for($i=0;$i<$len;$i++){
            if(rand(0,1)){
                $array[]=$a;
            }else{
                $array[]=$b;
            }
        }
        return $array;
    }
    //数组内所有的元素
    function max_count($array){
        //echo json_encode($array).'<hr>';
        $p=[];
        $max_count=0;
        $tmp='';
        for($i=0;$i<count($array);$i++){
            if(empty($tmp)){
                $tmp=$array[$i];
            }
    
            if($tmp==$array[$i]){
                $max_count++;
                if(isset($p[$array[$i]])){
                    if($p[$array[$i]]<$max_count){
                        $p[$array[$i]]=$max_count;
                    }
                }else{
                    $p[$array[$i]]=$max_count;
                }
                continue;
            }
    
            $i=$i-1;
            $max_count=0;
            $tmp='';
        }
        return $p;
    }
    //单独输出某个元素
    function max_count_b($b,$array){
        $max_count=0;
        $max_b=0;
        foreach($array as $v){
            if($b==$v){
                $max_count++;
                if($max_b<$max_count){
                    $max_b=$max_count;
                }
                continue;
            }
            $max_count=0;
        }
        return $max_b;
    
    }
    index();

    相关文章

      网友评论

          本文标题:求数组中某个元素连续出现的最大个数

          本文链接:https://www.haomeiwen.com/subject/zbhetctx.html