There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend.
The rules of the game are as follows:
Given the number of friends, n, and an integer k, return the winner of the game.
n | k | return |
---|---|---|
5 | 2 | 3 |
6 | 5 | 1 |
큐를 사용해서 접근했다. 큐에 n명의 친구들을 순서대로 넣어 원소가 하나만 남을 때까지 while문으로 반복했다. k번째가 아닌 친구들이 큐의 첫번째일 경우에는 popleft를 한 후, 다시 append로 뒤로 보냈다. 만약, k번째이면 append는 생략하고 popleft만 해서 큐에서 제거했다.
첫번째 예제의 경우 아래의 이미지와 같은 방식으로 적용된다.
from collections import deque
class Solution:
def findTheWinner(self, n: int, k: int) -> int:
q=deque([i for i in range(n)])
i=0
while len(q)>1:
if i!=k-1:
num=q.popleft()
q.append(num)
i+=1
else:
q.popleft()
i=0
return q[0]+1
결과