예제 #1
0
        public void AddNum(int num)
        {
            _minIntHeap.Push(num);
            _maxIntHeap.Push(_minIntHeap.Pop());

            if (_minIntHeap.GetSize() < _maxIntHeap.GetSize())
            {
                _minIntHeap.Push(_maxIntHeap.Pop());
            }
        }
예제 #2
0
        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);
        }
예제 #3
0
        private void AddImpl(int val)
        {
            if (val < _heap.Peek())
            {
                return;
            }

            _heap.Push(val);
            if (!_heap.IsFull())
            {
                return;
            }

            _heap.Pop();
        }
예제 #4
0
        public KthLargest(int k, int[] nums)
        {
            _heap = new MinIntHeap(k);

            for (int i = 0; i < k && i < nums.Length; i++)
            {
                _heap.Push(nums[i]);
            }


            for (int i = k; i < nums.Length; i++)
            {
                AddImpl(nums[i]);
            }
        }