C# Code with two foreach, beats 98.5%

  • 1
    public IList<int> TopKFrequent(int[] nums, int k)
    	var list = new List<int>(k);
    	var dict = new Dictionary<int, int>();
    	foreach (int num in nums)
    		if (!dict.ContainsKey(num)) dict.Add(num, 1);
    		else dict[num]++;
    	foreach (var kvp in dict.OrderByDescending(e => e.Value))
    		if (list.Count == list.Capacity) break;
    		else list.Add(kvp.Key);
    	return list;

Log in to reply

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