1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
// Runtime: 44 ms, faster than 62.77% of C++ online submissions for Majority Element.
// Memory Usage: 19.6 MB, less than 6.06% of C++ online submissions for Majority Element.
class Solution {
public:
int majorityElement(vector<int>& nums) {
return majorityElement(nums,0,nums.size()-1).first;
}
//递归函数,返回pair表示众数及其出现次数
pair<int,int> majorityElement(const vector<int> &nums,int l,int r){
//递归终点
if(l==r)
return {nums[l],1};
//取中点分治
int mid=(l+r)/2;
auto rl=majorityElement(nums,l,mid);
auto rr=majorityElement(nums,mid+1,r);
//左右两侧众数相等,直接返回众数和频率
if(rl.first==rr.first)
return {rl.first,rl.second+rr.second};
//左右两侧众数不相等,对两个众数的频率讨论
if(rl.second>rr.second)
//若左侧众数频率大,则结果是左侧众数,其出现的频率是左侧的频率(已求出)加右侧的频率(用count统计)
return {rl.first,rl.second+count(nums.begin()+mid+1,nums.begin()+r+1,rl.first)};
else
return {rr.first,rr.second+count(nums.begin()+l,nums.begin()+mid+1,rr.first)};
}
};
|