Javascript O(n) simple solution

  • 0
    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))

  • 0

    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.