zoukankan      html  css  js  c++  java
  • *Majority Element II

    题目:

    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.

    解题思路:

    Majority Elements不同是这里需要维护两个变量n1和n2,如果下一个数与这两个数都不同的时候,count1和count2都减一,如果下一个数与n1或者n2相等的时候,对应的count++。最后的结果必定在n1或者n2中。

    The basic idea is based on Moore's Voting Algorithm, we need two candidates with top 2 frequency. If meeting different number from the candidate, then decrease 1 from its count, or increase 1 on the opposite condition. Once count equals 0, then switch the candidate to the current number. The trick is that we need to count again for the two candidates after the first loop. Finally, output the numbers appearing more than n/3 times.

    public class Solution{
        public List<Integer> majorityElement(int[] nums){
            List<Integer> rst = new ArrayList<Integer>();
            if(nums == null || nums.length == 0) return rst;
            int count1 = 0, count2 = 0, candidate1 = 0, candidate2 = 1;
            for(int num : nums){
                if(num == candidate1) count1++;
                else if(num == candidate2) count2++;
                else if(count1 == 0){
                    candidate1 = num;
                    count1 = 1;
                }
                else if(count2 == 0){
                    candidate2 = num;
                    count2 = 1;
                }
                else{
                    count1--;
                    count2--;
                }
            }
            count1 = 0; count2 = 0;
            for(int num : nums){
                if(num == candidate1) count1+=1;
                else if(num == candidate2) count2 +=1;
            }
            if (count1 > nums.length/3 ) rst.add(candidate1);
            if (count2 > nums.length/3 ) rst.add(candidate2);
            return rst;
        }
    }

    https://leetcode.com/discuss/69126/concise-java-solution-based-on-moores-voting-algorithm

  • 相关阅读:
    vue3.0中如何使用ueditor
    如何在vue+element中实现选择框和穿梭框的根据拼音以及拼音首字母以及汉字的模糊搜索
    select 使其默认选中文本不为空
    java环境配置
    amaze ui 滚动监听
    vue项目中如何使用less
    强大的css3库
    input type file兼容性
    select中想要加a链接 并且新窗口打开
    echarts绘制k线图为什么写candlestick类型就报错
  • 原文地址:https://www.cnblogs.com/hygeia/p/4645611.html
Copyright © 2011-2022 走看看