Last active
May 12, 2016 11:59
-
-
Save whatvn/7f031b74fff3ffb137eb05b1a447e13b to your computer and use it in GitHub Desktop.
find 1 mil smallest number in 1 bil input number
This file contains hidden or 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
# origin question&answer | |
# http://www.vithon.org/2015/04/30/ph%E1%BB%8Fng-v%E1%BA%A5n:-tim-1-tri%E1%BB%87u-s%E1%BB%91-nh%E1%BB%8F-nh%E1%BA%A5t-trong-1-t%E1%BB%B7-s%E1%BB%91 | |
# the origin version use heapq | |
# this version do not use external module, but use sorted cheat when iterate through set (is not sorted) | |
def solve(inp, n=1000000): | |
print inp | |
heap = set() | |
for i in inp: | |
i = -i | |
if len(heap) < n: | |
heap.add(i) | |
else: | |
for m in sorted(heap): | |
if m < i and i not in heap: | |
heap.remove(m) | |
heap.add(i) | |
return [-x for x in heap] | |
assert(set(solve([1, 2, 3, 4, -5], 3)) == set([-5, 1, 2])) | |
assert(set(solve([5, 4, 3, 2, 1], 3)) == set([1, 2, 3])) | |
assert(set(solve([13, 4, 3, 2, 1, 100, 2000, 500], 5)) == set([1, 2, 3, 4, 13])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment