N개의 순서대로 쌓여있는 카드 중 가장 앞 카드 한개를 버리고 그 다음 첫번째 카드를 가장 아래로 쌓는 과정은 N-1번 수행하여 마지막 남는 카드를 return 한다
from collections import deque
N = int(input())
if N == 1:
print(1)
else:
cards = deque(list(range(1, N+1)))
while len(cards) > 1:
discard = cards.popleft()
topcard = cards.popleft()
cards.append(topcard)
print(cards[0])
위 코드는 244ms 의 런타임이 소요되었다.
from collections import deque
N = int(input())
if N == 1:
print(1)
else:
cards = deque(list(range(1, N+1)))
for _ in range(1, N):
discard = cards.popleft()
cards.append(cards.popleft())
print(cards[0])
위 코드는 152ms 런타임이 소요되었다.
두 코드의 가장 큰 차이는 for/while 문 사용 차이이다.
while의 경우 condition 문을 N-1번 계산해야하기 때문에 시간 소요가 커진다.
주어진 카드 개수에서 마지막 남은 카드 개수가 1개라는 점을 생각해보면, 버리는 행위는 N-1번으로 정해져 있다는 것을 알 수 있다.
따라서 이번 문제에서는 for문 사용이 적합하다