Ejemplo n.º 1
0
 // use max priority queue of size k
 // since insert/delete are O(lg k), time complexity O(N lg k)
 public static int KthSmallest(int[] a, int k)
 {
     MaxPQ pq = new MaxPQ(k);
     for (int i = 0; i < a.Length; i++)
     {
         if (i < k)
             pq.Insert(a[i]);
         else
             if (pq.GetMax() > a[i])
             {
                 pq.DeleteMax();
                 pq.Insert(a[i]);
             }
     }
     return pq.GetMax();
 }
Ejemplo n.º 2
0
        // use max priority queue of size k
        // since insert/delete are O(lg k), time complexity O(N lg k)
        public static int KthSmallest(int[] a, int k)
        {
            MaxPQ pq = new MaxPQ(k);

            for (int i = 0; i < a.Length; i++)
            {
                if (i < k)
                {
                    pq.Insert(a[i]);
                }
                else
                if (pq.GetMax() > a[i])
                {
                    pq.DeleteMax();
                    pq.Insert(a[i]);
                }
            }
            return(pq.GetMax());
        }