Created
April 4, 2019 23:12
-
-
Save jeremiq/4038d8c16fb890d35e4c1cf9186dd024 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import heapq | |
from typing import List | |
def kthsmallest1(l: List[int], k: int) -> int: # nlogk | |
if k > len(l): | |
return min(l) | |
l = [-1 * elt for elt in l] | |
h: List[int] = [] | |
# O(log k) | |
for elt in l[:k]: | |
heapq.heappush(h, elt) | |
for elt in l[k:]: | |
if elt in h: | |
pass | |
else: | |
# O(n log k) worst case | |
heapq.heappushpop(h, elt) | |
return -1*heapq.heappop(h) | |
def test_kth_smallest1(): | |
assert 3 == kthsmallest1(range(10), 4) | |
test_kth_smallest1() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment