Given a non-empty list of words, return the k most frequent elements.

Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

Example 1:
Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output: ["i", "love"]
Explanation: "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
Example 2:
Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
Output: ["the", "is", "sunny", "day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words,
with the number of occurrence being 4, 3, 2 and 1 respectively.
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Input words contain only lowercase letters.
Follow up:
Try to solve it in O(n log k) time and O(n) extra space.

先用 hashmap 存储string 和出现次数的映射, 然后insert并维持一个size为K的priorityqueue (注意要自己定义compare 函数),最后会得到top Kth words 但是是从小到大排序,注意要reverse:

class Solution {
public List<String> topKFrequent(String[] words, int k) {
if(words == null || words.length == 0 || k <= 0){
return new ArrayList<String>();
}
Map<String, Integer> map = new HashMap<>();
PriorityQueue<Map.Entry<String,Integer>> pq = new PriorityQueue<>((e1, e2) -> compareElement(e1,e2));
for(String str : words){
map.put(str, map.getOrDefault(str, 0)+1);
}
for(Map.Entry<String,Integer> entry : map.entrySet()){
pq.add(entry);
if(pq.size() > k){
pq.poll();
}
}
List<String> res = new ArrayList<>();
while(!pq.isEmpty()){
res.add(pq.poll().getKey());
}
Collections.reverse(res);
return res;
} private int compareElement(Map.Entry<String,Integer> e1, Map.Entry<String,Integer> e2){
if(e1.getValue() - e2.getValue() != 0)
{return e1.getValue() - e2.getValue();}
else
{return e2.getKey().compareTo(e1.getKey());}
}
}

  

LeetCode - Top K Frequent Words的更多相关文章

  1. [LeetCode] Top K Frequent Elements 前K个高频元素

    Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,2 ...

  2. [LeetCode] Top K Frequent Words 前K个高频词

    Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted b ...

  3. LeetCode "Top K Frequent Elements"

    A typical solution is heap based - "top K". Complexity is O(nlgk). typedef pair<int, un ...

  4. Top K Frequent Elements 前K个高频元素

    Top K Frequent Elements 347. Top K Frequent Elements [LeetCode] Top K Frequent Elements 前K个高频元素

  5. C#版(打败99.28%的提交) - Leetcode 347. Top K Frequent Elements - 题解

    版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址 http://blog.csdn.net/lzuacm. C#版 - L ...

  6. [leetcode]692. Top K Frequent Words K个最常见单词

    Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted b ...

  7. [leetcode]347. Top K Frequent Elements K个最常见元素

    Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...

  8. [LeetCode] 347. Top K Frequent Elements 前K个高频元素

    Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...

  9. 【LeetCode】692. Top K Frequent Words 解题报告(Python)

    [LeetCode]692. Top K Frequent Words 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/top ...

随机推荐

  1. unity中自制模拟第一人称视角

    public float sensitivityX = 5f; public float sensitivityY = 5f; public float sensitivetyKeyBoard = 0 ...

  2. 遍历所有子物体中renderer(渲染器)中的material(材质)并改变其alpha值实现若隐若现的效果

    using UnityEngine;using System.Collections;using UnityEngine.UI; public class CubeControl : MonoBeha ...

  3. day056 多表增加和查询

    今日总结: 多表的增删改查操作 多表操作 增 book id title book_detail publish author onetoone manytoone manytomany book_o ...

  4. Java多线程习题 ===重点 ,错题积累

    多线程重点,错题分析 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: . 12: 13: 14: 15:

  5. linux 在执行命令过程中,反单引号(`)这个符号代表的意义为何?

    在一串命令中,在`之内的命令将会被先执行,而且执行出来的结果将作为外部的输入信息.例如:uname -r 会显示出目前的内核版本,而我们的内核版本在/lib/modules里面,因此.你可以先执行un ...

  6. tf.nn.conv2d

    tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, name=None) input: 指需要做卷积的输入图像,它 ...

  7. :适配器模式:Adapter

    #ifndef __ADAPTER_H__ #define __ADAPTER_H__ #include <iostream> using namespace std; class Duc ...

  8. shell怎么判断两个文件内容是否相同

    #cat diff_two_file#/bin/sbinfile1=/mnt/mmc/test/aafile2=/mnt/mmc/test/bbdiff $file1 $file2 > /dev ...

  9. <Spark><Programming><Loading and Saving Your Data>

    Motivation Spark是基于Hadoop可用的生态系统构建的,因此Spark可以通过Hadoop MapReduce的InputFormat和OutputFormat接口存取数据. Spar ...

  10. VOOKI:一款免费的Web应用漏洞扫描工具

    Vooki是一款免费且用户界面友好的Web应用漏扫工具,它可以轻松地为你扫描任何Web应用并查找漏洞.Vooki主要包括三个部分,Web应用扫描器,Rest API扫描器以及报告.Web应用扫描器​V ...