Find k most frequent integers

PHOTO EMBED

Wed Feb 24 2021 22:35:52 GMT+0000 (UTC)

Saved by @GriffinDZ #java

public int[] topKFrequent(int[] nums, int k) {
        ArrayList<LinkedList<Integer>> freqList = new ArrayList<>();
        for (int i = 0; i <= nums.length; i++) {
            freqList.add(new LinkedList<Integer>());
        }
        
        HashMap<Integer, Integer> elementFreq = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (elementFreq.containsKey(nums[i])){
                elementFreq.put(nums[i], elementFreq.get(nums[i]) + 1);
            }
            else {
                elementFreq.put(nums[i], 1);
            }
        }
        
        Iterator<Integer> elemItr = elementFreq.keySet().iterator();
        while (elemItr.hasNext()) {
            int currKey = elemItr.next();
            freqList.get(elementFreq.get(currKey)).add(currKey);
        }
        
        ArrayList<Integer> intsByFreq = new ArrayList<>();
        for (int i = 0; i < freqList.size(); i++) {            
            LinkedList<Integer> currList = freqList.get(i);
            ListIterator<Integer> currListItr = currList.listIterator(0);
            while (currListItr.hasNext()) {
                intsByFreq.add(currListItr.next());
            }
        }
        
        int[] topK = new int[k];
        int topKIdx = 0;
        for (int i = intsByFreq.size() - 1; i >= intsByFreq.size() - k; i--) {
            topK[topKIdx] = intsByFreq.get(i);
            topKIdx++;
        }
        
        return topK;
    }
content_copyCOPY

Based on bucket sort