Home >Backend Development >PHP Problem >Leetcode PHP题解--D83 169. Majority Element

Leetcode PHP题解--D83 169. Majority Element

步履不停
步履不停Original
2019-06-10 09:19:071969browse

Leetcode PHP题解--D83 169. Majority Element

D83 169. Majority Element

Question link

169. Majority Element

Question analysis

Given an array, return the elements that appear more than half of the time.

Idea

Use the array_count_values ​​function to calculate the number of occurrences of elements, use arsort to sort the results in reverse order, and output the first one. (Related tutorial recommendations: php video tutorial)

Final code

<?php
class Solution {    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function majorityElement($nums) {
        $values = array_count_values($nums);
        arsort($values);        return key($values);
    }
}

The above is the detailed content of Leetcode PHP题解--D83 169. Majority Element. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Related articles

See more