zoukankan      html  css  js  c++  java
  • Majority Element III

    Given an array of integers and a number k, the majority number is the number that occurs more than 1/k of the size of the array, find all the majority elements.

    Example

    Given [3,1,2,3,2,3,3,4,4,4] and k=3, return [3].

    Challenge 

    O(n) time and O(k) extra space

     

    This is a generalized problem of Majority Number and Majority Number II. The key observation here is that we try to find k different numbers to hide. And each number is at most hide once. So even if there is a O(k) inner loop, the total operations is still O(N) not O(N * k).

        public List<Integer> majorityElements(int[] nums, int k) {
            Map<Integer, Integer> cnt = new HashMap<>();
            for(int i = 0; i < nums.length; i++) {
                cnt.put(nums[i], cnt.getOrDefault(nums[i], 0) + 1);
                if(cnt.size() == k) {
                    for(int key : cnt.keySet()) {
                        cnt.put(key, cnt.get(key) - 1);
                        if(cnt.get(key) == 0) {
                            cnt.remove(key);
                        }
                    }
                }
            }
            List<Integer> ans = new ArrayList<>();
            for(int key : cnt.keySet()) {
                cnt.put(key, 0);
            }
            for(int i = 0; i < nums.length; i++) {
                if(cnt.containsKey(nums[i])) {
                    cnt.put(nums[i], cnt.get(nums[i]) + 1);
                }
            }
            for(int key : cnt.keySet()) {
                if(cnt.get(key) > nums.length / k) {
                    ans.add(key);
                }
            }
            return ans;
        }

     

     

    Related Problems 

    Majority Element 

    Majority Element II 

     

  • 相关阅读:
    CalISBN.java
    Int2BinaryString.java
    PrintNumber.java
    AllSame.java
    第一个程序
    将博客搬至CSDN
    sqoop 1.4.4-cdh5.1.2快速入门
    hadoop的关键进程
    HIVE快速入门
    公钥,私钥和数字签名这样最好理解
  • 原文地址:https://www.cnblogs.com/lz87/p/7221377.html
Copyright © 2011-2022 走看看