leetcode-腾讯精选50题-38

mac2022-06-30  22

169. Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array. 想到哈希法,及用找到的数放入字典的键中,每多一次,值加一,最后输出值最大的键 官方题解给出了collections.Counter(nums)可以很好的执行

counts = collections.Counter(nums) return max(counts.keys(), key=counts.get)
最新回复(0)