zoukankan      html  css  js  c++  java
  • 摩尔投票法

    练习题目

    1. 多数元素
    2. 求众数 II

    以229题为例,给定一个大小为 n 的整数数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素,尝试设计时间复杂度为 O(n)、空间复杂度为 O(1)的算法解决此问题。

    我们可以很容易想到用map来解决该问题,但是不满足其复杂度要求,改用摩尔投票法来解决。
    摩尔投票法分为两步,第一步抵消阶段,选定候选人后,如果后续的人不一致则减少其投票,当其票数为0后,更换候选人;第二部得到所有的候选人后,遍历统计其出现次数,看看是否满足要求。

    class Solution {
        public List<Integer> majorityElement(int[] nums) {
            List<Integer> res = new ArrayList<>();
            if (nums.length==0) {
                return res;
            }
    
            int candidate1 = nums[0];
            int candidate2 = nums[0];
            int count1 = 0;
            int count2 = 0;
    
            for (int num:nums) {
                if (candidate1 == num) {
                    count1++;
                    continue;
                }
    
                if (candidate2 == num) {
                    count2++;
                    continue;
                }
    
                if (count1 == 0) {
                    count1++;
                    candidate1=num;
                    continue;
                }
    
                if (count2 == 0) {
                    count2++;
                    candidate2=num;
                    continue;
                }
    
                count1--;
                count2--;
            }
    
            count1=0;
            count2=0;
            for (int num:nums) {
                if (num == candidate1) {
                    count1++;
                } else if (num == candidate2) {
                    count2++;
                }
            }
    
            if (count1>nums.length/3) {
                res.add(candidate1);
            }
    
            if (count2>nums.length/3) {
                res.add(candidate2);
            }
    
            return res;
        }
    }
    
  • 相关阅读:
    Solaris 默认Shell 修改
    关系数组
    文件描述符 文件操作 <> open 文件句柄
    IO 双引号 输出 输入
    第五章答案
    子例程 subroutine
    钻石操作符
    花括号的使用 printf %${width}s , 否则会 去找 $widths
    print reverse <> 是打印全部的文件内容 ?
    hihoCoder#1239 Fibonacci
  • 原文地址:https://www.cnblogs.com/hunter-w/p/14255859.html
Copyright © 2011-2022 走看看