标签:public run ++ BMI memory sage cto max vector
一、题目说明
题目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.
标签:public run ++ BMI memory sage cto max vector
原文地址:https://www.cnblogs.com/siweihz/p/12275938.html