LeetCode version Problem
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.
class Solution { public ListLintCode version ProblemtopKFrequent(String[] words, int k) { List res = new ArrayList<>(); if (words.length < k) return res; Map map = new HashMap<>(); for (String word: words) { if (!map.containsKey(word)) map.put(word, 1); else map.put(word, map.get(word)+1); } PriorityQueue > queue = new PriorityQueue<>( (a, b) -> a.getValue() == b.getValue() ? b.getKey().compareTo(a.getKey()) : a.getValue() - b.getValue() ); for (Map.Entry entry: map.entrySet()) { queue.offer(entry); if (queue.size() > k) queue.poll(); } while (!queue.isEmpty()) { res.add(0, queue.poll().getKey()); } return res; } }
Find top k frequent words with map reduce framework.
The mapper"s key is the document id, value is the content of the document, words in a document are split by spaces.
For reducer, the output should be at most k key-value pairs, which are the top k words and their frequencies in this reducer. The judge will take care about how to merge different reducers" results to get the global top k frequent words, so you don"t need to care about that part.
The k is given in the constructor of TopK class.
NoticeFor the words with same frequency, rank them with alphabet.
/** * Definition of OutputCollector: * class OutputCollectorExample{ * public void collect(K key, V value); * // Adds a key/value pair to the output buffer * } * Definition of Document: * class Document { * public int id; * public String content; * } */
Given document A =
lintcode is the best online judge
I love lintcode
and document B =
lintcode is an online judge for coding interview
you can test your code online at lintcode
The top 2 words and their frequencies should be
lintcode, 4
online, 3
Map Reduce
Solution// Use Pair to store k-v pair class Pair { String key; int value; Pair(String k, int v) { this.key = k; this.value = v; } } public class TopKFrequentWords { public static class Map { public void map(String _, Document value, OutputCollectoroutput) { // Output the results into output buffer. // Ps. output.collect(String key, int value); String content = value.content; String[] words = content.split(" "); for (String word : words) { if (word.length() > 0) { output.collect(word, 1); } } } } public static class Reduce { private PriorityQueue Q = null; private int k; private Comparator pairComparator = new Comparator () { public int compare(Pair o1, Pair o2) { if (o1.value != o2.value) { return o1.value - o2.value; } //if the values are equal, compare keys return o2.key.compareTo(o1.key); } }; public void setup(int k) { // initialize your data structure here this.k = k; Q = new PriorityQueue (k, pairComparator); } public void reduce(String key, Iterator values) { int sum = 0; while (values.hasNext()) { sum += values.next(); } Pair pair = new Pair(key, sum); if (Q.size() < k) { Q.add(pair); } else { Pair peak = Q.peek(); if (pairComparator.compare(pair, peak) > 0) { Q.poll(); Q.add(pair); } } } public void cleanup(OutputCollector output) { // Output the top k pairs into output buffer. // Ps. output.collect(String key, Integer value); List pairs = new ArrayList (); while (!Q.isEmpty()) { pairs.add(Q.poll()); } // reverse result int n = pairs.size(); for (int i = n - 1; i >= 0; --i) { Pair pair = pairs.get(i); output.collect(pair.key, pair.value); } // while (!Q.isEmpty()) { // Pair pair = Q.poll(); // output.collect(pair.key, pair.value); // } } } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/68159.html
Problem Given two sentences words1, words2 (each represented as an array of strings), and a list of similar word pairs pairs, determine if two sentences are similar. For example, great acting skills a...
摘要:使用,利用其按層次操作的性質,可以得到最優解。這樣可以保證這一層被完全遍歷。每次循環取出的元素存為新的字符串。一旦找到和相同的字符串,就返回轉換序列長度操作層數,即。 Problem Given two words (start and end), and a dictionary, find the length of shortest transformation sequence...
摘要:描述給定一個非空的整數數組,返回其中出現頻率前高的元素。然后以元素出現的次數為值,統計該次數下出現的所有的元素。從最大次數遍歷到次,若該次數下有元素出現,提取該次數下的所有元素到結果數組中,知道提取到個元素為止。 Description Given a non-empty array of integers, return the k most frequent elements. E...
Problem Given a non-empty array of integers, return the k most frequent elements. Example Given [1,1,1,2,2,3] and k = 2, return [1,2]. Note You may assume k is always valid, 1 ≤ k ≤ number of unique e...
摘要:題目要求假設有一個非空的整數數組,從中獲得前個出現頻率最多的數字。先用來統計出現次數,然后將其丟到對應的桶中,最后從最高的桶開始向低的桶逐個遍歷,取出前個頻率的數字。 題目要求 Given a non-empty array of integers, return the k most frequent elements. For example, Given [1,1,1,2,2,...
閱讀 1225·2021-11-11 16:54
閱讀 1738·2021-10-13 09:40
閱讀 933·2021-10-08 10:05
閱讀 3498·2021-09-22 15:50
閱讀 3701·2021-09-22 15:41
閱讀 1782·2021-09-22 15:08
閱讀 2338·2021-09-07 10:24
閱讀 3571·2019-08-30 12:52