Accepted JavaScript solution


  • 1
    N
    var topKFrequent = function(nums, k) {
        var groups={};
    	nums.forEach(function(value){
    	     groups[value]= ( groups[value]+1)|| 1;
    	});
    	var result= [];	
    	Object.keys(groups).sort(function(a,b){return groups[b]-groups[a]}).
            slice(0,k).	forEach(x=> {
    		result.push(parseInt(x));
    	});
    	return result;
    };

  • 0
    J

    Do you know how to calculate the time complexity for this? I had something more verbose, but somewhat similar:

    var topKFrequent = function(nums, k) {
        
        var hash = {};
        var sortedObjs = [];
        var topFreqEls = [];
        
      // loop through each element in array, assign to hash key if doesnt exist, otherwise increment count which will keep track of most frequent elements
        for(var i = 0; i < nums.length; i++){
            if(!hash[nums[i]]){
                hash[nums[i]] = 1;
            } else {
                hash[nums[i]] += 1;
            }
        }
      
      for(var key in hash){
        if(hash.hasOwnProperty(key)){
          sortedObjs.push({
            num: key, count: hash[key]
          });
        }
      } 
      
      //sorts descending order by object's 'count' value
      sortedObjs.sort(function(a,b){
        return b.count - a.count;
      })
      
      var topFreqEls = sortedObjs.slice(0,k).map(function(el){
        return parseInt(el.num);
      })
      
      return topFreqEls;
    };
    

Log in to reply
 

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