Created
October 31, 2021 03:06
-
-
Save ttungl/1a0da024b8be47ff65203bc5eccfd146 to your computer and use it in GitHub Desktop.
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
| def merge_two_arrays_3(a,b): ## len_a=n, len_b=m, m>n | |
| # n is length of a; m is length of b | |
| # time O(m+n) space O(n+m) | |
| from collections import deque # first in first out | |
| da = deque(a) | |
| db = deque(b) | |
| res = [] | |
| while len(da) or len(db): | |
| if da and db: | |
| xa = da.popleft() # O(1) | |
| xb = db.popleft() | |
| if xa > xb: | |
| res.append(xb) | |
| da.appendleft(xa) # O(1) | |
| else: | |
| res.append(xa) | |
| db.appendleft(xb) | |
| elif da and not db: | |
| xa = da.popleft() | |
| res.append(xa) # O(1) | |
| elif db and not da: | |
| xb = db.popleft() | |
| res.append(xb) | |
| return res | |
| a = [1,3,4] | |
| b = [2,3,5,6] | |
| print(merge_two_arrays_3(a, b)) | |
| # [1, 2, 3, 3, 4, 5, 6] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment