// if the slide window rule out our head element // then pop it, else pop nothing, as we do not cache // them actaully publicvoidpoll(int val) { if ( val == deque.peek()) { deque.poll(); } }
// for every new added element, try to add them into the queue // if they are less then any elements, just add it at the last // else delete those less than it, as they are meanningless now
publicvoidadd(int val) { // note here, we need to remain the same large element within the queue // if here we use val >= deque.last, we would rule out the same large element while (!deque.isEmpty() && val > deque.peekLast()) { deque.removeLast(); } deque.addLast(val); }
// since we maintain such a queue that the head element is always our // maximum value in this window publicintpeek() { return deque.peek(); }
classSolution { publicint[] topKFrequent(int[] nums, int k) {
// step 1 : count the frequence of each element Map<Integer, Integer> map = newHashMap<>(); for (inti=0; i < nums.length; i++) { if (map.containsKey(nums[i])){ map.put(nums[i], map.get(nums[i]) + 1); }else { map.put(nums[i], 1); } }
// step 2 : sort the frequences List<Map.Entry<Integer, Integer>> list = newArrayList<>(map.entrySet()); // can use lambda expression to simplify the declaration of the comparator // list.sort((o1,o2)-> (- o1.getValue().compareTo(o2.getValue()))); list.sort(newComparator<Map.Entry<Integer, Integer>>() { @Override publicintcompare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2){ // the defult order is natrual order i.e. increasing order return -o1.getValue().compareTo(o2.getValue()); } });
// steo 3 : output the ans int[] ans = newint[k]; for (inti=0; i < k; i++) { ans[i] = list.get(i).getKey(); }
// step 1 : count the frequence of each element Map<Integer, Integer> map = newHashMap<>(); for (inti=0; i < nums.length; i++) { map.put(nums[i], map.getOrDefault(nums[i], 0) + 1); }
// step 2 : sort the frequences PriorityQueue<int[]> pq = newPriorityQueue<>((pair1,pair2)->pair1[1]-pair2[1]); for (Map.entry<Integer, Integer> entry : map.entrySet()) { if (pq.size() < k) { pq.add(newint[]{entry.getKey(), entry.getValue()}); }else { if (entry.getValue() > pq.peek()[1]){ pq.poll(); pq.add(entry); } } }
// steo 3 : output the ans int[] ans = newint[k]; for (inti= k - 1; i >= 0; i--) { ans[i] = pq.poll()[0]; }