コード例 #1
0
        public void Push(HeapNodeWord node)
        {
            if (++tail >= arr.Length)
            {
                throw new Exception("Heap is full");
            }

            arr[tail] = node;

            int currentIndex = tail;
            int parentIndex  = GetParentIndex(currentIndex);

            while (parentIndex >= 0 && FirstIsGreater(arr[parentIndex], arr[currentIndex]))
            {
                arr[currentIndex] = arr[parentIndex];
                arr[parentIndex]  = node;

                currentIndex = parentIndex;
                parentIndex  = GetParentIndex(currentIndex);
            }
        }
コード例 #2
0
        public IList <string> TopKFrequent(string[] words, int k)
        {
            var dict = new Dictionary <string, int>();

            foreach (var word in words)
            {
                dict[word] = dict.ContainsKey(word) ? dict[word] + 1 : 1;
            }

            var heap = new MinHeap(k + 1);

            foreach (var key in dict.Keys)
            {
                var node = new HeapNodeWord();
                node.count = dict[key];
                node.word  = key;

                heap.Push(node);

                if (heap.Count > k)
                {
                    heap.Pop();
                }
            }

            var res = new List <string>();

            while (heap.Count > 0)
            {
                var node = heap.Pop();
                res.Insert(0, node.word);
                //res.Add(node.word);
            }

            return(res);
        }
コード例 #3
0
 public MinHeap(int size)
 {
     arr = new HeapNodeWord[size];
 }
コード例 #4
0
 private bool FirstIsGreater(HeapNodeWord node1, HeapNodeWord node2)
 {
     return((node1.count == node2.count) ?
            String.Compare(node1.word, node2.word) == -1 // -1  aaa < zzz
         : node1.count > node2.count);
 }