예제 #1
0
        public int MinMeetingRooms(Interval[] intervals)
        {
            Array.Sort(intervals, new Comparison <Interval>((i1, i2) => i2.start.CompareTo(i1.start)));
            var rooms = new MinHeap(int.MaxValue);

            foreach (var interval in intervals)
            {
                if (rooms.PeekMin() <= interval.start)
                {
                    rooms.ExtractMin();
                    rooms.InsertKey(interval.end);
                }
                else
                {
                    rooms.InsertKey(interval.end);
                }
            }

            return(rooms._data.Count);
        }
        // head1 -> 1 -> 2 -> 3
        // head2 -> 7 -> 9 -> 11
        // head3 -> 4 -> 6 -> 10
        public ListNode MergeKLists(ListNode[] lists)
        {
            var dummyHead = new ListNode(-1);
            var runner    = dummyHead;

            var minHeap = new MinHeap();

            for (var head = 0; head < lists.Length; head++)
            {
                if (lists[head] != null)
                {
                    minHeap.Insert(new HeapItem()
                    {
                        data      = lists[head].val,
                        listIndex = head
                    });
                    lists[head] = lists[head].next;
                }
            }

            while (minHeap.Count() > 0)
            {
                var minFromHeap         = minHeap.ExtractMin();
                var minItemListNextNode = lists[minFromHeap.listIndex];
                if (minItemListNextNode != null)
                {
                    minHeap.Insert(new HeapItem()
                    {
                        data      = minItemListNextNode.val,
                        listIndex = minFromHeap.listIndex
                    });
                    lists[minFromHeap.listIndex] = lists[minFromHeap.listIndex].next;
                }
                var node = new ListNode(minFromHeap.data);
                runner.next = node;
                runner      = runner.next;
            }

            return(dummyHead.next);
        }