1 题目
寻找数组中次数多于⌊n/2⌋次的元素,即主元素/众数
题目链接:点击打开链接
2 思路和实现
(1) 分治算法:
将数组分为左右两边,分别找出左右两边的主元素并计算其出现的频率,对比频率找出每个小问题的主元素,递归调用完成算法。
class Solution {
public:
int majorityElement(vector<int>& nums) {
return maj(nums, 0, nums.size() - 1);
}
int maj(vector<int>& nums, int start, int end) {
if(start == end)
return nums[start];
int majority;
int lefMaj = maj(nums, start, start + (end-start) / 2);
int rgtMaj = maj(nums, start + (end- start) / 2 + 1, end);
int lefMajFre = countFre(nums, start, end, lefMaj);
int rgtMajFre = countFre(nums, start, end, rgtMaj);
if (lefMajFre > rgtMajFre)
majority = lefMaj;
else majority = rgtMaj;
return majority;
}
//
int countFre(vector<int>&nums, int start, int end, int target) {
int count = 0;
for(int i = start; i <= end; i++)
if(target == nums[i])
count++;
return count;
}
};
(2)投票算法
用一个变量主元素最后一定会 设定两个变量maj和count,maj保存当前可能的主元素,count保存其出现的次数。
遍历数组,如果num[i]与maj相同,则count + 1,否则count - 1,当count = 0时,将maj赋值为当前遍历到的元素。
最后留下的count值大于0的元素就是主元素。
class Solution {
public:
int majorityElement(vector<int>& nums) {
int count = 1,
maj = nums[0];
for(int i = 1; i < nums.size(); i++) {
if(count == 0)
maj = nums[i];
if(maj == nums[i])
count++;
else count--;
}
return maj;
}
};