Javascript Solution


  • 0
    S
    var topKFrequent = function(nums, k) {
      let hashMap = {};	
      findFrequency(nums, hashMap);
      return sortObjects(hashMap, k);
    };
    
    function sortObjects(hashMap, k) {
    	let sortedKeys = Object.keys(hashMap);
    	sortedKeys.sort((a, b) => {
      	return hashMap[b] - hashMap[a];
      });
      return sortedKeys.map(Number).slice(0, k).sort();
    }
    
    function findFrequency(nums, hashMap) {
    	if(nums.length === 1) {
      	if(!hashMap[nums[0]]) {
        	hashMap[nums[0]] = 1;
        }
        else {
        	hashMap[nums[0]] += 1;
        }
      	return 1;
      }
      let mid = Math.floor(nums.length / 2);
      let midArray = nums.slice(0, mid);
      let lengthArray = nums.slice(mid);
      findFrequency(midArray, hashMap);
      findFrequency(lengthArray, hashMap);
    }
    

Log in to reply
 

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