zoukankan      html  css  js  c++  java
  • LeetCode 347. Top K Frequent Elements (前K个高频元素)

    题目标签:HashMap, Heap

      题目给了我们一组数字,让我们找出 k 个 最多出现的数字。

      先把数字和出现次数存入hashmap,然后遍历map里的数字,利用priorityQueue,按照出现次数 从小到大的顺序依次把数字 加入 queue。当达到k个数字后,把剩下的都去除。

      最后output的 array,里面顺序是不影响的。

    Java Solution:

    Runtime: 43 ms, faster than 38% 

    Memory Usage: 41 MB, less than 32%

    完成日期:04/04/2019

    关键点:PriorityQueue

    class Solution {
        public List<Integer> topKFrequent(int[] nums, int k) {
            
            Map<Integer, Integer> map = new HashMap<>();
            List<Integer> result = new ArrayList<>();
            
            // put number and count into map
            for(int num : nums) {
                map.put(num, map.getOrDefault(num, 0) + 1);
            }
            
            // define priorityQueue
            PriorityQueue<Integer> heap = 
                new PriorityQueue<Integer>((n1, n2) -> map.get(n1) - map.get(n2));
            
            // put each number into heap
            for(int num : map.keySet()) {
                heap.add(num);
                
                if(heap.size() > k) // keep k numbers in the heap
                    heap.poll();
            }
            
            // put heap numbers into list
            while(!heap.isEmpty()) {
                result.add(heap.poll());
            }
            
            return result;
        }
    }

    参考资料:LeetCode Discuss

    LeetCode 题目列表 - LeetCode Questions List

    题目来源:https://leetcode.com/

  • 相关阅读:
    ASP.NET常见命名空间及其功能描述
    C#中的里氏替换原则
    Java中的split函数的用法
    shader之旅-7-平面阴影(planar shadow)
    OpenGL三角形的双面不同颜色的绘制
    MATLAB squeeze 函数
    matlab 常用函数汇总
    第一个OpenGL程序
    Github 留言系统
    Paging 简单自由的分页生成器
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/11136060.html
Copyright © 2011-2022 走看看