Javascript O(n) simple solution


  • 0
    P
    var topKFrequent = function(nums, k) {
        return Object.entries(
                nums.reduce((d,v)=> (d[v]=1+(d[v]||0)) && d, {})
            )
            .reduce((ordered,[k,v])=> {
                let ary=ordered[v]||[];
                return ary.push(k) && (ordered[v]=ary) && ordered;
            }, Array(nums.length))
            .filter(xs=>!!xs)
            .reduceRight((acc,xs)=>acc.concat(xs))
            .slice(0,k)
            .map(parseInt);
    };
    

  • 0
    S

    I like your solution but I'm curious as to how the last line works...when you pass parseInt to map, it'll end up receiving the index of each number as the base and won't work out properly. You can also do away with the .filter line because empty array elements are completely non-existent and won't even be looked at by .map, .forEach, .filter, or .reduce. Nice work, though!


Log in to reply
 

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