leetcode每日一题系列-求众数II-「摩尔投票」

222 阅读1分钟

leetcode-229-求众数II

[博客链接]

菜🐔的学习之路

掘金首页

[题目链接]

题目链接

[github地址]

github地址

[题目描述]

给定一个大小为 n 的整数数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。

 

 

示例 1:

输入:[3,2,3]
输出:[3]

示例 2:

输入:nums = [1]
输出:[1]

示例 3:

输入:[1,1,1,3,3,2,2,2]
输出:[1,2]

提示:

  • 1<=nums.length<=51041 <= nums.length <= 5 * 10^4
  • 109<=nums[i]<=109-109^ <= nums[i] <= 10^9  

进阶:尝试设计时间复杂度为 O(n)、空间复杂度为 O(1)的算法解决此问题。

思路一:摩尔投票

  • 摩尔投票可以求得超过一半数量元素
  • 同时也可以求出超过n/k这种数量元素的
  • 通过两次扫描
    • 第一次扫描求出可能满足条件的k-1个元素本题为两个元素a、b
    • 第二次扫描判断是否满足条件
public List<Integer> majorityElement(int[] nums) {
           List<Integer> res = new ArrayList<>();
           int k = nums.length / 3;
           int a = 0, b = 0;
           int c1 = 0, c2 = 0;
           for (int i : nums) {
               if (c1 != 0 && a == i) {
                   c1++;
               } else if (c2 != 0 && b == i) {
                   c2++;
               } else if (c1 == 0 && ++c1 >= 0) a = i;
               else if (c2 == 0 && ++c2 >= 0) b = i;
               else {
                   c1--;
                   c2--;
               }
           }
           c1 = 0;
           c2 = 0;
           for (int i : nums) {
               if (a == i) c1++;
               else if (b == i) c2++;
           }
           if (c1 > k) res.add(a);
           if (c2 > k) res.add(b);

           return res;
       }
  • 时间复杂度O(n)
  • 空间复杂度O(1)