zoukankan      html  css  js  c++  java
  • [转载]力扣229 求众数II 摩尔投票

    题目链接

    代码

    class Solution {
        public List<Integer> majorityElement(int[] nums) {
            // 创建返回值
            List<Integer> res = new ArrayList<>();
            if (nums == null || nums.length == 0) return res;
            // 初始化两个候选人candidate,和他们的计票
            int cand1 = nums[0], count1 = 0;
            int cand2 = nums[0], count2 = 0;
    
            // 摩尔投票法,分为两个阶段:配对阶段和计数阶段
            // 配对阶段
            for (int num : nums) {
                // 投票
                if (cand1 == num) {
                    count1++;
                    continue;
                }
                if (cand2 == num) {
                    count2++;
                    continue;
                }
    
                // 第1个候选人配对
                if (count1 == 0) {
                    cand1 = num;
                    count1++;
                    continue;
                }
                // 第2个候选人配对
                if (count2 == 0) {
                    cand2 = num;
                    count2++;
                    continue;
                }
    
                count1--;
                count2--;
            }
    
            // 计数阶段
            // 找到了两个候选人之后,需要确定票数是否满足大于 N/3
            count1 = 0;
            count2 = 0;
            for (int num : nums) {
                if (cand1 == num) count1++;
                else if (cand2 == num) count2++;
            }
    
            if (count1 > nums.length / 3) res.add(cand1);
            if (count2 > nums.length / 3) res.add(cand2);
    
            return res;
        }
    }
    
    // 作者:wotxdx
    // 链接:https://leetcode-cn.com/problems/majority-element-ii/solution/liang-fu-dong-hua-yan-shi-mo-er-tou-piao-fa-zui-zh/
    // 来源:力扣(LeetCode)
    // 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
    
  • 相关阅读:
    Java 学习资料
    01 html5
    vscode 插件推荐
    08 css高级
    07 css定位
    06 css布局浮动
    05 css盒子
    04 css复合选择器 标签 行高
    03 css字体样式
    02 css基础选择器
  • 原文地址:https://www.cnblogs.com/bears9/p/13862008.html
Copyright © 2011-2022 走看看