題目鏈接:
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;
}
};