题目链接:
https://leetcode.com/problems/majority-element/description/
描述
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
算法思想:
可以使用STL中的map来解决这个问题比较方便,如果使用数组来解决对于负数和最大数特别大时将无能为力。使用map的first来存储nums中的数据,second来存储其个数。
源代码
/*
Author:杨林峰
Date:2017.12.30
LeetCode(169):主元
*/
class Solution {
public:
int majorityElement(vector<int>& nums) {
map<int,int> m;
int sz = nums.size();
for(int i = 0;i < sz;i++)
{
m[nums[i]]++;
}
map<int,int>::iterator it;
for(map<int,int>::iterator it = m.begin();it != m.end();it++)
{
if(!(sz%2) && it->second >= sz/2 || it->second > sz/2)
{
return it->first;
}
}
return 0;
}
};