您的位置:首页 > 其它

leetcode刷题日记——Majority Element

2015-12-17 19:57 155 查看
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.

问题分析:题目的目标就是找出整数数组中出现的次数大于⌊ n/2 ⌋ 的元素,这类问题比较简单,使用一个map对里面的元素计数既可以,然后比较每个元素出现的次数是否大于n/2.

实现代码如下:

class Solution {
public:
int majorityElement(vector<int>& nums) {
map<int,int> count;
int n=nums.size();
int majority;
for(int i=0;i<n;i++){
count[nums[i]]++;
}
map<int,int>::iterator it;
for(it=count.begin();it!=count.end();++it){
if(it->second>(n/2)) return it->first;
}
return 0;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: