C# HashMap and bucket sort, with LINQ

  • 0

    Same idea of Bucket Sort and HashMap, just with some Linq usage to show reduced code. Also, the frequency map built is actually a reverse map, to facilitate easier Linq query.

    public class Solution {
        public IList<int> TopKFrequent(int[] nums, int k) {
            var pairs = nums.GroupBy(num => num).Select(g => new KeyValuePair<int, int>(g.Count(), g.Key));
            List<int>[] frequencyMap = new List<int>[nums.Length];
            foreach (var pair in pairs) {
                var key = nums.Length - pair.Key;
                if (frequencyMap[key] == null) {
                    frequencyMap[key] = new List<int>();
            return frequencyMap.Where(entry => entry != null).SelectMany(entry => entry).Take(k).ToList();

Log in to reply

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