- 解题思路
- 利用哈希表记录数组的元素的个数
- 求出数组长度的一半size
- 遍历哈希表,如果有元素大于size,则找到了
- 代码
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param numbers int整型vector
* @return int整型
*/
int MoreThanHalfNum_Solution(vector<int>& nums)
{
// write code here
unordered_map<int,int> hash;
for(auto& e : nums)
{
hash[e]++;
}
int size = nums.size() / 2;
int ret = 0;
for(auto& e : hash)
{
if(e.second > size)
{
ret = e.first;
break;
}
}
return ret;
}
};

京公网安备 11010502036488号