Title (19 years headline autumn sign scene hand-torn code, that's right so terrible...) ___________
If there are 500 million users in the tremble, there will be 500 million records for each user to open the tremble once, and if each user opens the tremble twice, there will be 1 billion records. That is to say, every time a user opens a tremble, he records his uid.
Question: Find out the top 10 users who turn on tremolo most frequently.
General thinking
Refer to this blogger, the idea is clear!!! https://www.cnblogs.com/qlky/p/7512199.html
- Use a hashmap to count the number of UIDs that have appeared
- Priority Queue is used to achieve priority queue, with the maximum number of k occurrences.
- Corresponding to hashmap, find the k UIDs that appear most.
ps: I think 2, 3 can be merged into one step, but I really don't know how to achieve it.==
My code -- version 1.0
package topKQues; import java.util.ArrayList; import java.util.Comparator; import java.util.PriorityQueue; import java.util.HashMap; import java.io.FileReader; import java.io.IOException; import java.io.BufferedReader; public class TopKwithPriorityQueue<E extends Comparable> { static String filepath = "/Users/alicelmx/java_workspace/algorithm_java8/src/topKQues/demo.txt"; PriorityQueue<E> queue ; static int K ; public TopKwithPriorityQueue(int maxSize) { if (maxSize <= 0) throw new IllegalArgumentException(); this.K = maxSize; this.queue = new PriorityQueue<>(maxSize, new Comparator<E>() { @Override public int compare(E o1, E o2) { // Using o1-o2 in small root heap return (o1.compareTo(o2)); } }); } public void add(E e) { if(queue.size() < K) queue.add(e); else { E peek = queue.peek(); if(e.compareTo(peek) > 0) { queue.poll(); queue.add(e); } } } public ArrayList<E> sortedList() { ArrayList<E> list = new ArrayList<E>(queue); return list; } public static HashMap<String,Integer> readAndConvert() { HashMap<String,Integer> map = new HashMap<String,Integer>(); try { FileReader fr = new FileReader(filepath); BufferedReader bf = new BufferedReader(fr); String str; // Read strings by line while ((str = bf.readLine()) != null) { if(!map.containsKey(str)) map.put(str,1); else { int time = map.get(str); map.put(str,time+1); } } bf.close(); fr.close(); } catch (IOException e) { e.printStackTrace(); } return map; } public static void main(String[] args) { HashMap<String,Integer> map = readAndConvert(); TopKwithPriorityQueue pq = new TopKwithPriorityQueue(2); for(String key: map.keySet()) pq.add(map.get(key)); ArrayList<String> res = new ArrayList<>(); for(int i=0;i<pq.sortedList().size();i++) { for(String key:map.keySet()) { if(map.get(key).equals(pq.sortedList().get(i))&&!res.contains(key)) res.add(key); } } System.out.println(res); } }