- Majority Element My Submissions QuestionEditorial Solution
Total Accepted: 110538 Total Submissions: 268290 Difficulty: Easy
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.
Subscribe to see which companies asked this question
思路:so easy
class Solution {
public:
int majorityElement(vector<int>& nums) {
map<int,int> m;
int n=nums.size();
if(n==1)return nums[0];
for(int i=0;i<nums.size();++i){
if(m.count(nums[i])){
m[nums[i]]++;
if(m[nums[i]]>nums.size()/2)return nums[i];
}
else m[nums[i]]=1;
}
}
};