题目摘自LeetCode:
169. Majority Element
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.
class Solution {
public:
int majorityElement(vector<int>& nums)
{
return findMajority(nums,0,nums.size()-1);
}
int findMajority(vector<int>& nums, int lo, int hi)
{
if(lo==hi)//基本情况,只有一个元素时它就是Majority
{
return nums[lo];
}
else
{
int mid=lo+(hi-lo)/2;
int lm=findMajority(nums,lo,mid);
int rm=findMajority(nums,mid+1,hi);
if(lm==rm)// 如果lm和rm是一样的,返回
{
return lm;
}
else// 否则应该统计lm和rm出现的次数,选择次数多的那个
{
int lm_cnt=count(nums.begin()+lo,nums.begin()+hi+1,lm);
int rm_cnt=count(nums.begin()+lo,nums.begin()+hi+1,rm);
if(lm_cnt>rm_cnt)
{
return lm;
}
else
{
return rm;
}
}
}
}
};