博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Majority Element II 求众数之二
阅读量:7061 次
发布时间:2019-06-28

本文共 1262 字,大约阅读时间需要 4 分钟。

 

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

Hint:

  1. How many majority elements could it possibly have?
  2. Do you have a better hint? !

 

这道题让我们求出现次数大于n/3的众数,而且限定了时间和空间复杂度,那么就不能排序,也不能使用哈希表,这么苛刻的限制条件只有一种方法能解了,那就是摩尔投票法 Moore Voting,这种方法在之前那道题中也使用了。题目中给了一条很重要的提示,让我们先考虑可能会有多少个众数,经过举了很多例子分析得出,任意一个数组出现次数大于n/3的众数最多有两个,具体的证明我就不会了,我也不是数学专业的。那么有了这个信息,我们使用投票法的核心是找出两个候选众数进行投票,需要两遍遍历,第一遍历找出两个候选众数,第二遍遍历重新投票验证这两个候选众数是否为众数即可,选候选众数方法和前面那篇一样,由于之前那题题目中限定了一定会有众数存在,故而省略了验证候选众数的步骤,这道题却没有这种限定,即满足要求的众数可能不存在,所以要有验证。代码如下:

 

class Solution {public:    vector
majorityElement(vector
& nums) { vector
res; int m = 0, n = 0, cm = 0, cn = 0; for (auto &a : nums) { if (a == m) ++cm; else if (a ==n) ++cn; else if (cm == 0) m = a, cm = 1; else if (cn == 0) n = a, cn = 1; else --cm, --cn; } cm = cn = 0; for (auto &a : nums) { if (a == m) ++cm; else if (a == n) ++cn; } if (cm > nums.size() / 3) res.push_back(m); if (cn > nums.size() / 3) res.push_back(n); return res; }};

 

类似题目:

 

参考资料:

 

转载地址:http://miyll.baihongyu.com/

你可能感兴趣的文章