Last active
July 17, 2017 18:36
-
-
Save agnaite/03ca48672cc1333be5fa9932b83e7634 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
# You are given 2 sorted arrays A and B | |
# A has enough placeholders at the end to hold B | |
# Write a method to merge B into A in sorted order | |
# i.e. | |
# A = [3, 6, 8] | |
# B = [2, 5, 10, 11] | |
# => [2, 3, 5, 6, 8, 10, 11] | |
def get_last_item_index(arr): | |
"""Return the index of the last item in array""" | |
index = None | |
for i, item in enumerate(arr): | |
if not item: | |
break | |
index = i | |
return index | |
def merge_into_a(a, b): | |
"""Merge list B into list A.""" | |
index_a = get_last_item_index(a) | |
index_b = get_last_item_index(b) | |
index_buffer = len(a) - 1 | |
while index_b >= 0: | |
if index_buffer > 0 and a[index_a] > b[index_b]: | |
a[index_buffer] = a[index_a] | |
index_a -= 1 | |
else: | |
a[index_buffer] = b[index_b] | |
index_b -= 1 | |
index_buffer -= 1 | |
return a | |
a = [3, 6, 8, None, None, None, None] | |
b = [2, 5, 10, 11] | |
print merge_into_a(a, b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment