Created
May 5, 2012 11:21
-
-
Save israelst/2601661 to your computer and use it in GitHub Desktop.
Merging two ordered lists
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
def merge(x, y): | |
if len(x) == 0: | |
return y | |
if len(y) == 0: | |
return x | |
last = y.pop() if x[-1] < y[-1] else x.pop() | |
# 'merged' is required because the append method is in place | |
merged = merge(x, y) | |
merged.append(last) | |
return merged |
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
def merge(x, y): | |
if len(x) == 0: | |
return y | |
if len(y) == 0: | |
return x | |
if x[0] <= y[0]: | |
return [x[0]] + merge(x[1:], y) | |
else: | |
return [y[0]] + merge(x, y[1:]) | |
Adicionei uma solução sem slice e concat.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
O problema é que se estamos falando de listas do python, slice e concat custam O(n), o que faz com que seu algoritmo seja O(n^2), que perde todo o sentido.