Skip to content

Commit

Permalink
Update 347-Top-K-Frequent-Elements.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
KostiantynPopovych committed Aug 26, 2022
1 parent f8912c5 commit a11886a
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions typescript/347-Top-K-Frequent-Elements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,17 @@ function topKFrequent(nums: number[], k: number): number[] | undefined {
}
}
}

// The short one solution using map & sorting
function topKFrequent(nums: number[], k: number): number[] {
const map = nums.reduce((acc, num) => {
const currentNumber = acc[String(num)];
acc[num] = currentNumber ? currentNumber + 1 : 1;
return acc;
}, {});

return Object.entries(map)
.sort(([, countA], [, countB]) => (countB as number) - (countA as number))
.slice(0, k)
.map(([num]) => +num);
};

0 comments on commit a11886a

Please sign in to comment.