692. Top K Frequent Words
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.
Approach #1: C++.[unordered_map]
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
if (words.empty()) return {};
unordered_map<string, int> m;
for (string word : words) {
m[word]++;
}
vector<pair<string, int>> temp(m.begin(), m.end());
sort(temp.begin(), temp.end(), cmp);
vector<string> ans;
for (int i = 0; i < k; ++i) {
ans.push_back(temp[i].first);
}
return ans;
}
private:
static bool cmp(pair<string, int> a, pair<string, int> b) {
if (a.second == b.second) return a.first < b.first;
return a.second > b.second;
}
};
Approach #2: Java. [heap]
class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> count = new HashMap();
for (String word : words) {
count.put(word, count.getOrDefault(word, 0) + 1);
}
PriorityQueue<String> heap = new PriorityQueue<String>(
(w1, w2)->count.get(w1).equals(count.get(w2)) ?
w2.compareTo(w1) : count.get(w1) - count.get(w2) );
for (String word : count.keySet()) {
heap.offer(word);
if (heap.size() > k) heap.poll();
}
List<String> ans = new ArrayList();
while (!heap.isEmpty()) ans.add(heap.poll());
Collections.reverse(ans);
return ans;
}
}
Approach #3: Python.
import collections
import heapq
class Solution:
# Time Complexity = O(n + nlogk)
# Space Complexity = O(n)
def topKFrequent(self, words, k):
count = collections.Counter(words)
heap = []
for key, value in count.items():
heapq.heappush(heap, Word(value, key))
if len(heap) > k:
heapq.heappop(heap)
res = []
for _ in range(k):
res.append(heapq.heappop(heap).word)
return res[::-1] class Word:
def __init__(self, freq, word):
self.freq = freq
self.word = word def __lt__(self, other):
if self.freq == other.freq:
return self.word > other.word
return self.freq < other.freq def __eq__(self, other):
return self.freq == other.freq and self.word == other.word
692. Top K Frequent Words的更多相关文章
- 【LeetCode】692. Top K Frequent Words 解题报告(Python)
[LeetCode]692. Top K Frequent Words 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/top ...
- [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 ...
- #Leetcode# 692. Top K Frequent Words
https://leetcode.com/problems/top-k-frequent-words/ Given a non-empty list of words, return the k mo ...
- [LC] 692. Top K Frequent Words
Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted b ...
- [leetcode]692. Top K Frequent Words频率最高的前K个单词
这个题的排序是用的PriorityQueue实现自动排列,优先队列用的是堆排序,堆排序请看:http://www.cnblogs.com/stAr-1/p/7569706.html 自定义了优先队列的 ...
- [leetcode]347. Top K Frequent Elements K个最常见元素
Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...
- [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 ...
- 347. Top K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,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 ...
随机推荐
- [C++] 递归之全排列问题、半数集
一.递归的定义 一个过程或函数在其定义或说明中又直接或间接调用自身的一种方法,它通常把一个大型复杂的问题层层转化为一个原问题相似的规模较小的问题来求解. 二.用递归求解问题的主要步骤 1.找出相似性 ...
- 机器学习:集成学习(集成学习思想、scikit-learn 中的集成分类器)
一.集成学习的思想 集成学习的思路:一个问题(如分类问题),让多种算法参与预测(如下图中的算法都可以解决分类问题),在多个预测结果中,选择出现最多的预测类别做为该样本的最终预测类别: 生活中的集成思维 ...
- 删除pool error的解决方法
标签(空格分隔): ceph,ceph运维,pool 问题描述: 删除pool的时候提示下面的错误: [root@node3 ~]# ceph osd pool delete ecpool ecpoo ...
- 一段小程序理解getchar和putchar
#include "stdafx.h" #include <iostream> using namespace std; int main() { char c,d,e ...
- 将CDM中所有以Relatonship_开头的关系全部重命名,避免生成数据库因为重复关系名报错
Option Explicit ValidationMode = True InteractiveMode = im_Batch Dim mdl '当前model '获取当前活 ...
- vue中父子组件传递信息实现
为了能够在父子组件中实现双向控制,需要以下的步骤: 第一步:子组件中挖坑 (1)在需要父组件填充具体内容的地方挖坑,方式为 <slot name="message">& ...
- 正则表达式 notes
nfs 网络文件系统 存储类型:块存储,对象存储,文件存储 nfs属于文件存储 crond 分钟小时日月周 命令:绝对路径 命令是由crond解释 /bin/bash a.sh */2 * * * * ...
- Oracle——基础知识(一)
一.Oracle中的数据类型 1.字符串类型.如:char.nchar.varchar2.nvarchar2.2.数值类型.如:int.number(p,s).integer.smallint. ...
- C语言学习笔记--指针阅读技巧
1. 指针阅读技巧:右左法则 (1)从最里层的圆括号中未定义的标示符看起 (2)首先往右看,再往左看 (3)遇到圆括号或方括号时可以确定部分类型,并调转方向 (4)重复 2.3 步骤,直到阅读结束 注 ...
- javaScript之动态样式
动态添加样式可以实现更好的视觉效果和交互效果,下面就介绍一下如何动态和删除样式: 方法一.使用obj.className来修改样式表的类名 obj.className = “style1”; ...