JavaScript O(n) easy to understand solution


  • 0
    var topKFrequent = function(nums, k) {
        if (nums == null || nums.length <= 1 || k < 1) return nums; // special situation checks
        
        let map = new Map(), list = [], res = [], temp;
        
        // Get frequency of each unique child into the Map
        for (let i = 0; i < nums.length; i++) {
            if (map.has(nums[i])) { // child is in the Map
                temp = map.get(nums[i]);
                temp++;
            } else { // child is not in the Map
                temp = 1;
            }
            map.set(nums[i], temp);
        }
        
        // Put map key-value pairs into 2D array for sorting
        map.forEach(function(val, key, map) {
            list.push([key, val]);
        });
        
        // Sort 2D array by the frequency of each child of nums[]
        list.sort(function(a, b) {
           return b[1] - a[1];
        });
        
        // Generate result
        for (let i = 0; i < k; i++) {
            res.push(list[i][0]);
        }
        
        return res;
    };
    

Log in to reply
 

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