[leetcode]347. Top K Frequent Elements

2023-05-16

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]

Note:

  • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

Solution:

class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        if(nums == null || nums.length == 0) {
            return list;
        }
        Map<Integer, Integer> map = new HashMap();
        for(int num : nums) {
            if(map.containsKey(num)) {
                map.put(num, map.get(num)+1);
            }else {
                map.put(num,1);   
            }
        }
        
        return map.entrySet().stream().sorted((e1,e2) -> {
            if(e1.getValue() > e2.getValue()) {
                return -1;
            }else if(e1.getValue() < e2.getValue()){
                return 1;
            }else {
                return 0;
            }
        }).limit(k).map(e -> e.getKey()).collect(Collectors.toList());
        
        
    }
}

把map变为list。

比较大小的时候,a和b比较,如果你觉得a应该比较大,那么返回一个正值;b比较大,那么返回一个负值;一样大,就返回0。

以上为从小到大排序。如果要从小到大,相反即可。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

[leetcode]347. Top K Frequent Elements 的相关文章

  • AQS理解

    AbstractQueuedSynchronizer简称AQS xff0c 是一个用于构建锁和同步容器的框架 事实上concurrent包内许多类都是基于AQS构建 xff0c 例如ReentrantLock Semaphere Count
  • B树、B+树及索引

    B树 xff1a 每个节点都存储key和data xff0c 所有节点组成这棵树 xff0c 并且叶子节点指针为null B 43 树 xff1a 只有叶子节点存储data xff0c 叶子节点包含了这棵树的所有键值 xff0c 叶子节点不
  • Arrays.sort和Collections.sort实现原理解析

    Collections sort方法底层就是调用的Arrays sort方法 写一个例子看源码 xff1a public static void main String args List lt String gt strings 61 A
  • Java代理模式之动态代理

    代理模式是设计模式中非常重要的一种类型 代理模式从类型上来说 xff0c 可以分为静态代理和动态代理两种类型 假设一个场景 xff0c 有一个蛋糕店 xff0c 卖的蛋糕都是用蛋糕机做的 xff0c 而且不同种类的蛋糕由不同的蛋糕机来做 x

随机推荐

  • 二叉树镜像

    求二叉树镜像 public class Solution public void Mirror TreeNode root if root 61 61 null return if root left 61 61 null amp amp
  • 设计模式之适配器模式

    适配器模式是作为两个不兼容的接口之间的桥梁 这种类型的设计模式属于结构型模式 xff0c 它结合了两个独立接口的功能 这种模式涉及到一个单一的类 xff0c 该类负责加入独立的或不兼容的接口功能 举个真实的例子 xff0c 读卡器是作为内存
  • 设计模式之单例模式

    1 懒汉式 xff0c 线程不安全 public class Demo1 private static Demo1 instance private Demo1 public static Demo1 getInstance if inst
  • Lambda表达式详解

    Java 8最值得学习的特性就是Lambda表达式 Lambda写的好可以极大减少代码冗余 xff0c 同时可读性也好过冗长的内部类 xff0c 匿名类 举例说明一下 xff1a xff08 1 xff09 创建线程传统写法 xff1a T
  • Android8.0以上实现APP(应用)开机自启动

    一 程序中实现APP开机自启动 可参考 xff1a https www cnblogs com jetereting p 4572302 html 二 设置APP开机自启动权限 小米手机设置开机启动应用权限 xff08 Android9 0
  • 跳台阶问题

    1 输出斐波那契数列的第n项 直接上代码 xff1a public class Fibonacci public static int fibonacci int n if n 61 61 0 return 0 if n 61 61 1 r
  • 字符串编辑距离

    字符串的编辑距离 xff0c 又称为Levenshtein距离 是利用字符操作 xff0c 把字符串A转换成字符串B所需要的最少操作数 其中 xff0c 字符操作包括 xff1a 删除一个字符插入一个字符修改一个字符 例如对于 34 hel
  • [leetcode]807.Max Increase to Keep City Skyline

    In a 2 dimensional array grid each value grid i j represents the height of a building located there We are allowed to in
  • [leetcode]1038. Binary Search Tree to Greater Sum Tree

    Given the root of a binary search tree with distinct values modify it so that every node has a new value equal to the su
  • [leetcode]344. Reverse String

    Write a function that reverses a string The input string is given as an array of characters char Do not allocate extra s
  • [leetcode]136. Single Number

    Given a non empty array of integers every element appears twice except for one Find that single one Note Your algorithm
  • [leetcode]412. Fizz Buzz

    Write a program that outputs the string representation of numbers from 1 to n But for multiples of three it should outpu
  • [leetcode]94. Binary Tree Inorder Traversal

    Given a binary tree return the inorder traversal of its nodes 39 values Example Input 1 null 2 3 1 2 3 Output 1 3 2 Solu
  • [leetcode]46. Permutations

    Given a collection of distinct integers return all possible permutations Example Input 1 2 3 Output 1 2 3 1 3 2 2 1 3 2
  • [ERROR][idea报错]Unmapped Spring configuration files found.

    idea启动Event Log提示 xff1a Spring Configuration Check Unmapped Spring configuration files found Please configure Spring fac
  • (备忘)android模拟器摄像头模拟

    Camera分Front Camera和Back Camera 通常我们模拟后摄像头就可以了 三个选项 none 表示没有摄像头 打开摄像应用会崩溃 emulated 系统模拟一个动态的画面 在黑白格背景上随机移动的矩形色块 Webcam
  • [leetcode]22. Generate Parentheses

    Given n pairs of parentheses write a function to generate all combinations of well formed parentheses For example given
  • [leetcode]238. Product of Array Except Self

    Given an array nums of n integers where n gt 1 return an array output such that output i is equal to the product of all
  • [ERROR]ubuntu18.04安装Postman报错

    解压完成以后 xff0c 进入解压目录 xff0c 执行 Postman xff0c 提示 xff1a Postman error while loading shared libraries libgconf 2 so 4 cannot
  • [leetcode]347. Top K Frequent Elements

    Given a non empty array of integers return the k most frequent elements Example 1 Input nums 61 1 1 1 2 2 3 k 61 2 Outpu