zoukankan      html  css  js  c++  java
  • LeetCode 347 Top K Frequent Elements

    方法1: 声明新的类 + hashmap + priority queue

     1 class Solution {
     2     public List<Integer> topKFrequent(int[] array, int k) {
     3         Queue<Result> queue = new PriorityQueue<Result>(newComparator);
     4         Map<Integer, Integer> map = new HashMap<>();
     5         for (int i = 0; i < array.length; i++) {
     6             if (map.containsKey(array[i])) {
     7                 map.put(array[i], map.get(array[i]) + 1);
     8             } else {
     9                 map.put(array[i], 1);
    10             }
    11         }
    12         for(int i : map.keySet()) {
    13             queue.offer(new Result(i, map.get(i)));
    14         }
    15 
    16         List<Integer> res = new ArrayList<>();
    17         for (int i = 0; i < k; i++) {
    18             res.add(queue.poll().val);
    19         }
    20         return res;
    21     }
    22 
    23     public Comparator<Result> newComparator = new Comparator<Result>() {
    24         public int compare(Result a, Result b) {
    25             if (a.freq == b.freq) {
    26                 return 0;
    27             }
    28             //-1是倒向排序, 1是正向排序
    29             return a.freq > b.freq ? -1 : 1;
    30         }    
    31     };
    32 }
    33 
    34 class Result {
    35     int val, freq;
    36     public Result(int val, int freq) {
    37         this.val = val;
    38         this.freq = freq;
    39     }
    40 }
  • 相关阅读:
    浅谈prufer编码
    数据结构训练之三
    博弈论训练之一
    动态规划训练之十三
    杂题训练之七
    奇技淫巧训练之八
    浅谈博弈论
    浅谈卡特兰数
    奇技淫巧训练之七
    浅谈概率期望的一些例题
  • 原文地址:https://www.cnblogs.com/mayinmiao/p/8503703.html
Copyright © 2011-2022 走看看