刷题169. Majority Element
Posted siweihz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了刷题169. Majority Element相关的知识,希望对你有一定的参考价值。
一、题目说明
题目169. Majority Element,给定n个数的数组,返回出现次数超过半数的元素。
二、我的解答
这个题目用一个map,遍历一遍数组,计数每个元素出现的次数。
class Solution{
public:
int majorityElement(vector<int>& nums){
unordered_map<int,int> ump;
int maxNum = 0;
int maxCount = 0;
for(int i=0;i<nums.size();i++){
ump[nums[i]]++;
if(maxCount<ump[nums[i]]) {
maxCount = ump[nums[i]];
maxNum = nums[i];
}
}
return maxNum;
}
};
性能如下:
Runtime: 28 ms, faster than 32.81% of C++ online submissions for Majority Element.
Memory Usage: 11.2 MB, less than 15.15% of C++ online submissions for Majority Element.
三、优化措施
上面用的是unordered_map,改用map实现:
Runtime: 20 ms, faster than 82.58% of C++ online submissions for Majority Element.
Memory Usage: 11.2 MB, less than 39.39% of C++ online submissions for Majority Element.
通过超过半数,实现:
class Solution{
public:
int majorityElement(vector<int>& nums){
map<int,int> ump;
int half = (nums.size()+1)/2;
for(int i=0;i<nums.size();i++){
ump[nums[i]]++;
if(ump[nums[i]]>=half){
return nums[i];
}
}
return -1;
}
};
性能如下:
Runtime: 24 ms, faster than 54.42% of C++ online submissions for Majority Element.
Memory Usage: 11.1 MB, less than 63.64% of C++ online submissions for Majority Element.
以上是关于刷题169. Majority Element的主要内容,如果未能解决你的问题,请参考以下文章