public IList <int> TopKFrequent(int[] nums, int k) { var occurences = new Dictionary <int, int>(); foreach (var num in nums) { if (occurences.ContainsKey(num)) { occurences[num]++; } else { occurences.Add(num, 1); } } var heap = new MinIntHeap(k); foreach (var kvp in occurences) { heap.Push(kvp); } var result = new List <int>(); while (k != 0) { result.Add(heap.Pop().Key); k--; } return(result); }
public void AddNum(int num) { _minIntHeap.Push(num); _maxIntHeap.Push(_minIntHeap.Pop()); if (_minIntHeap.GetSize() < _maxIntHeap.GetSize()) { _minIntHeap.Push(_maxIntHeap.Pop()); } }
private void AddImpl(int val) { if (val < _heap.Peek()) { return; } _heap.Push(val); if (!_heap.IsFull()) { return; } _heap.Pop(); }