Ejemplo n.º 1
0
        /// <summary>
        /// 4. Median of Two Sorted Arrays
        /// <summary>
        public double FindMedianSortedArrays(int[] nums1, int[] nums2)
        {
            var totalLength = nums1.Length + nums2.Length;

            if (totalLength == 1)
            {
                return(nums1.Length > 0 ? nums1[0] : nums2[0]);
            }

            var sizeDiff = totalLength % 2;
            var minHeap  = new MinHeap(totalLength + 1);
            var maxHeap  = new MaxHeap(totalLength + 1);

            foreach (var n in nums1)
            {
                BuildHeap(minHeap, maxHeap, n);
            }
            foreach (var n in nums2)
            {
                BuildHeap(minHeap, maxHeap, n);
            }
            while (maxHeap.Size() != minHeap.Size() + sizeDiff)
            {
                if (maxHeap.Size() > minHeap.Size() + sizeDiff)
                {
                    minHeap.Offer(maxHeap.Poll());
                }
                else
                {
                    maxHeap.Offer(minHeap.Poll());
                }
            }

            return(sizeDiff == 0 ? (minHeap.Peek() + maxHeap.Peek()) / 2.0 : maxHeap.Peek());
        }
Ejemplo n.º 2
0
 private void BuildHeap(MinHeap minHeap, MaxHeap maxHeap, int n)
 {
     if (maxHeap.IsEmpty() || n <= maxHeap.Peek())
     {
         maxHeap.Offer(n);
     }
     else
     {
         minHeap.Offer(n);
     }
 }
Ejemplo n.º 3
0
 public void TestMaxHeapAdd()
 {
     maxHeap.Offer(10);
     maxHeap.Offer(12);
     maxHeap.Offer(13);
     maxHeap.Offer(9);
     maxHeap.Offer(5);
     maxHeap.Offer(15);
     Console.WriteLine("current top is: " + maxHeap.Peek());
 }