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

  • 相关阅读:
    Search Insert Position
    Substring with Concatenation of All Words
    Swap Nodes in Pairs
    Remove Element
    Remove Duplicates from Sorted Array
    Letter Combinations of a Phone Number
    Remove Nth Node From End of List
    Valid Parentheses
    Merge k Sorted Lists
    Using an Interface as a Type
  • 原文地址:https://www.cnblogs.com/hygeia/p/4645611.html
Copyright © 2011-2022 走看看