1
1
1
2
2
3
[0][1][2][3][4][5]
Count + sort
▸1given arr, k; count ← {}2for v in arr:3 count[v] ← count[v] + 14entries ← sort count by frequency desc5result ← first k values of entries6return result
state
- k2
- count{}
Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.
Try one problemGiven an integer array and a number k, return the k most frequent elements. The answer is guaranteed to be unique; it may be returned in any order.
▸1given arr, k; count ← {}2for v in arr:3 count[v] ← count[v] + 14entries ← sort count by frequency desc5result ← first k values of entries6return result
line 1Return the 2 most frequent values in the array. First we need to know how often each value appears.