Java solution using inverted index


  • 0
    C
    public class Solution {
        public List<Integer> topKFrequent(int[] nums, int k) {
            int length = nums.length;
    
            // Build a frequency map
            Map<Integer, Integer> map = new HashMap<>();
            for (int i=0; i<length; i++) {
                if (!map.containsKey(nums[i])) {
                    map.put(nums[i], 1);
                } else {
                    map.put(nums[i], map.get(nums[i])+1);
                }
            }
            
            // Build an inverted index of the frequency map
            java.util.TreeMap<Integer, List<Integer>> invertedIndex = new java.util.TreeMap<>();
            for (Integer key : map.keySet()) {
                int freq = map.get(key);
                if (!invertedIndex.containsKey(freq)) {
                    List<Integer> keys = new ArrayList<>();
                    keys.add(key);
                    invertedIndex.put(freq, keys);
                } else {
                    invertedIndex.get(freq).add(key);
                }
            }
            
            // Output the top K
            int i = 0;
            List<Integer> result = new ArrayList<>();
            for (Integer freq : invertedIndex.descendingKeySet()) {
                for (Integer key : invertedIndex.get(freq)) {
                    if (i >= k) {
                        return result;
                    }
                    result.add(key);
                    i++;
                }
            }
            return result;
        }
    }
    

    Simple but not the fastest solution. Execution time ~45ms.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.