// 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(); }
// 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()); }