zoukankan      html  css  js  c++  java
  • [LC] 347. Top K Frequent Elements

    Given a non-empty array of integers, return the k most frequent elements.

    Example 1:

    Input: nums = [1,1,1,2,2,3], k = 2
    Output: [1,2]
    

    Example 2:

    Input: nums = [1], k = 1
    Output: [1]

    class Solution {
        public List<Integer> topKFrequent(int[] nums, int k) {
            Map<Integer, Integer> map = new HashMap<>();
            for (Integer num: nums) {
              map.put(num, map.getOrDefault(num, 0) + 1);
            }
            // keep a top frequency heap
            PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>((a, b) -> 
              a.getValue() == b.getValue() ? b.getKey().compareTo(a.getKey()): a.getValue() - b.getValue()
            );
            for (Map.Entry<Integer, Integer> entry: map.entrySet()) {
                pq.offer(entry);
                if (pq.size() > k) {
                    pq.poll();
                }
            }
            List<Integer> res = new ArrayList<>();
            // while (!pq.isEmpty()) {
            //     res.add(0, pq.poll().getKey());
            // }
            while (!pq.isEmpty()) {
                res.add(pq.poll().getKey());
            }
            return res;
        }
    }
    public class Solution {
      public String[] topKFrequent(String[] combo, int k) {
        // Write your solution here.
        Map<String, Integer> map = new HashMap<>();
        for (String s: combo) {
          map.put(s, map.getOrDefault(s, 0) + 1);
        }
        PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>(k, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> a, Map.Entry<String, Integer> b) {
              return a.getValue().compareTo(b.getValue());
            }
        });
        for (Map.Entry<String, Integer> mymap: map.entrySet()) {
          pq.offer(mymap);
          if (pq.size() > k) {
            pq.poll();
          }
        }
        String[] res = new String[pq.size()];
        for (int i = res.length - 1; i >= 0; i--) {
          res[i] = pq.poll().getKey();
        }
        return res;
      }
    }
  • 相关阅读:
    FPGA边缘检测
    Luogu P5856 【「SWTR-03」Game】
    Luogu P4707 【重返现世】
    Weight Balanced Leafy Tree
    Luogu P4311 【士兵占领】
    Luogu P4174 【[NOI2006]最大获利】
    Luogu P1646 【[国家集训队]happiness】
    Luogu P4313 【文理分科】
    Luogu P4249 【[WC2007]剪刀石头布】
    Luogu P2754 【[CTSC1999]家园 / 星际转移问题】
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12315324.html
Copyright © 2011-2022 走看看