Leetcode--347. 前k个高频元素
发布日期:2021-04-30 21:02:19 浏览次数:103 分类:精选文章

本文共 1517 字,大约阅读时间需要 5 分钟。

????????????????????????k???????????????????

????

  • ???????????HashMap????????????????
  • ????????????????????????????
  • ????????????????????????????????????????
  • ???k?????????????k???????????
  • ???????????O(n + k log k)???n???????k??????k???????????????????O(n log n)?

    ????

    import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.Map;import java.util.Comparator;public class Solution {    private static List
    topKFrequent(int[] nums, int k) { Map
    map = new HashMap<>(); for (int num : nums) { if (map.containsKey(num)) { map.put(num, map.get(num) + 1); } else { map.put(num, 1); } } List
    > entryList = new ArrayList<>(map.entrySet()); Collections.sort(entryList, new Comparator
    >() { @Override public int compare(Map.Entry
    item1, Map.Entry
    item2) { return item2.getValue() - item1.getValue(); } }); ArrayList
    result = new ArrayList<>(); int j = 0; for (Map.Entry
    entry : entryList) { if (j >= k) { break; } result.add(entry.getKey()); j++; } return result; } private static final Comparator
    > mapComparator = new Comparator
    >() { @Override public int compare(Map.Entry
    item1, Map.Entry
    item2) { return item2.getValue() - item1.getValue(); } };}

    ????

  • ????????????HashMap??????????
  • ????????????????????????????
  • ???????????????????????????????????????
  • ???k?????????????k??????????????
  • ????????????????????????????

    上一篇:JDK源码随笔之AtomicInteger
    下一篇:如何在Android-Studio下进行NDK开发,吐血整理

    发表评论

    最新留言

    逛到本站,mark一下
    [***.202.152.39]2026年06月09日 07时40分41秒