4. 두 리스트 합치기

이세진·2022년 4월 15일
0

코테준비

목록 보기
14/87

생성일: 2022년 1월 11일 오후 4:58

구현 코드

# 두 리스트 합치기
import sys
sys.stdin = open("input.txt", "rt")

n = int(input())
firstList = list(map(int, input().split()))
m = int(input())
secondList = list(map(int, input().split()))

result = firstList + secondList
result.sort()

for x in result:
    print(x, end=" ")

모범 답안

import sys
sys.stdin=open("input.txt", "r")
n=int(input())
a=list(map(int, input().split()))
m=int(input())
b=list(map(int, input().split()))
p1=p2=0
c=[]
while p1<n and p2<m:
    if a[p1]<b[p2]:
        c.append(a[p1])
        p1+=1
    else:
        c.append(b[p2])
        p2+=1
if p1<n:
    c=c+a[p1:]
if p2<m:
    c=c+b[p2:]
for x in c:
    print(x, end=' ')

차이점

  • 내가 구현한 코드에서는 파이썬 문법을 활용하여 두 리스트를 더하고 sorting 했지만 답안에서는 두 변수를 활용(인덱스를 나타냄)하여 한 칸씩 크기를 비교하고 결과 리스트에 하나의 아이템 씩 추가하는 방식을 사용하였다.
profile
나중은 결코 오지 않는다.

0개의 댓글