您的位置:首页 > 其它

LeetCode 169. Majority Element (Easy)

2017-09-19 23:48 495 查看

题目描述:

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的数组,找出“主要元素”:出现次数多于⌊ n/2 ⌋次的元素。

思路:哈希一下,再遍历哈希表即可。

c++代码:

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