[LeetCode] 169. Majority Element

Easy
Related Topics: Array / Hash Table / Divide and Conquer / Sorting / Counting
LeetCode Source

解题想法

暴力解,统计所有数字出现的个数,选出现次数最多就是答案。

Python

class Solution:    def majorityElement(self, nums: List[int]) -> int:        c = Counter(nums)        return c.most_common()[0][0]

Python 直接作弊用 Counter,但当然时间花费就高
透过 most_common(),我们可以得知出现次数最多的数字。

C++

class Solution {public:    int majorityElement(vector<int>& nums) {        std::unordered_map<int, int> map;        for (auto i : nums) {            if (map.find(i) == map.end())                map[i] = 1;            else                map[i] += 1;        }        int res, count = 0;        for (auto n : map) {            if (count < n.second) {                res = n.first;                count = n.second;            }        }        return res;    }};

C++ 透过 unordered_map<int, int> 统计数字和它出现的次数
统计完后,再跑一个迴圈找最大值

这系列文被记录在 Top Interview 150 Series


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章