面试题 17.10. 主要元素
							面试题 17.10. 主要元素
数组中占比超过一半的元素称之为主要元素。给定一个整数数组,找到它的主要元素。若没有,返回-1。
示例 1:
输入:[1,2,5,9,5,9,5,5,5]
输出:5示例 2:
输入:[3,2]
输出:-1示例 3:
输入:[2,2,1,1,1,2,2]
输出:2说明:
你有办法在时间复杂度为 O(N),空间复杂度为 O(1) 内完成吗?代码如下:
class Solution {
    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function majorityElement($nums) {
        $countValues = array_count_values($nums);
        $count = count($nums);
        $max = max($countValues);
        return $max > $count / 2 ?  array_search($max, $countValues) : -1;
    }
}