Array of size n, with one element n/2 times

前端 未结 9 711
离开以前
离开以前 2021-02-04 12:41

Given an array of n integers, where one element appears more than n/2 times. We need to find that element in linear time and constant extra space.

YAAQ: Yet another arra

9条回答
  •  礼貌的吻别
    2021-02-04 13:05

    in php---pls check if it's correct

    function arrLeader( $A ){
    $len = count($A);
    $B = array();
    $val=-1;
    $counts = array_count_values(array); //return array with elements as keys and occurrences of each element as values
    for($i=0;$i<$len;$i++){
        $val = $A[$i];
        if(in_array($val,$B,true)){//to avoid looping again and again
        }else{
         if($counts[$val]>$len/2){
          return $val;
         }
         array_push($B, $val);//to avoid looping again and again
        }
     }
     return -1;
    }
    

提交回复
热议问题