面试题 17.10. 主要元素

地址:https://leetcode-cn.com/problems/find-majority-element-lcci/

<?php
/**
 * Created by PhpStorm.
 * User: huahua
 * Date: 2020/10/10
 * Time: 下午3:53
面试题 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) {
        $arr = array_count_values($nums);
        $count = count($nums);
        arsort($arr);
        $key = key($arr);
        $first= array_shift($arr);
        if ($first >= ceil($count/2)){
            return $key;
        }else{
            return -1;
        }

    }
}

 

posted @ 2020-10-10 15:54  花花妹子。  阅读(108)  评论(0编辑  收藏  举报