题目描述:
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;
}
}
}
};
本文介绍了一种寻找数组中主要元素的方法,即出现次数超过数组长度一半的元素。通过使用哈希表进行计数并遍历的方式,高效地解决了该问题。

517

被折叠的 条评论
为什么被折叠?



