Home >Backend Development >PHP Problem >Leetcode PHP题解--D83 169. Majority Element
D83 169. Majority Element
Question link
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!