11728. 배열합치기

sen·2021년 8월 12일
0

BOJ

목록 보기
25/38
post-thumbnail

문제

백준 11728번 배열합치기


풀이

아마 대부분이 투포인터를 처음 접할 때 두 배열을 합치는 걸로 시작하지 않을까?

n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = []

ai, bi = 0, 0
while True:
    if a[ai] <= b[bi]:
        c.append(a[ai])
        ai += 1
    else:
        c.append(b[bi])
        bi += 1
    if ai == len(a): break
    if bi == len(b): break
if ai < len(a): c += a[ai:]
if bi < len(b): c += b[bi:]

for x in c: print(x, end=' ')

처음에 이렇게 input() 함수 쓰고, 반복문 내에서 출력했는데,

n, m = map(int, sys.stdin.readline().split())
a = list(map(int, sys.stdin.readline().split()))
b = list(map(int, sys.stdin.readline().split()))
c = []

ai, bi = 0, 0
while True:
    if a[ai] <= b[bi]:
        c.append(a[ai])
        ai += 1
    else:
        c.append(b[bi])
        bi += 1
    if ai == len(a): break
    if bi == len(b): break
if ai < len(a): c += a[ai:]
if bi < len(b): c += b[bi:]

res = ''
for x in c: res += str(x) + ' '
print(res)

이렇게 sys.stdin.readline()으로 입력받고, 변수 res에 저장하고 출력했더니

시간도 메모리도 줄었다!

profile
공부 아카이브

0개의 댓글