Most common element in an array / Finding the relative majority, deterministically in O(n) time and O(1) space?

后端 未结 4 1257
暗喜
暗喜 2021-01-17 17:18

So for example, the answer for the array:

1, 11, 3, 95, 23, 8, 1

would be 1, since all the other elements only occur once while 1 occurs twice.

A lo

4条回答
  •  执笔经年
    2021-01-17 17:35

    this is my script to read most common element in an array

     $max) {
                    $max = $tempval[$i];
                }
            }
            //get value 
            for ($i = 0; $i <= count($tempval) - 1; $i++) {
                if ($tempval[$i] == $max) {
                    $this->keyVal = $tempval[$i];
                    $this->keyPlace = $i;
                    break;
                }
            }
    
            // 1.place holder on array $this->keyPlace;
            // 2.number of reapeats $this->keyVal;
            return $array[$this->keyPlace];
        }
    
    }
    
    $catch = new TestClass();
    $array = array(1, 1, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3, 1, 2, 3, 1, 1, 2, 5, 7, 1, 9, 0, 11, 22, 1, 1, 22, 22, 35, 66, 1, 1, 1);
    echo $catch->maxused_num($array);
    

提交回复
热议问题