程序员面试算法求数组众数

版权声明:转载请注明来源 https://blog.csdn.net/u013702678/article/details/88393060

给定一个大小为 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在众数。

示例 1:

输入: [3,2,3]
输出: 3

示例 2:

输入: [2,2,1,1,1,2,2]
输出: 2
class Solution {

    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function majorityElement($nums) {
        $tempOut = [];
        $count = count($nums);
        
        foreach($nums as $num)
        {
            if(isset($tempOut[$num]))
            {
                $tempOut[$num] ++;
                if($tempOut[$num]>($count/2)) 
                {
                    return $num;
                }
            } else {
                $tempOut[$num] = 1;
            } 
        }
        
        return key($tempOut);//解决只有一个元素的问题
    }
}

猜你喜欢

转载自blog.csdn.net/u013702678/article/details/88393060