알고리즘/알고리즘 문제풀이
큐_LeetCode_find-the-winner-of-the-circular-game
Downey
2021. 8. 26. 19:43
https://leetcode.com/problems/find-the-winner-of-the-circular-game/submissions/
문제 접근
1. 1...n의 Array를 생성. -> friendQueue
2. friendQueue의 count가 1이 아닌 동안 반복.
3. 반복 내용 -> k는 자기 자신을 포함하여 계산하므로, moves = k - 1
4. whereIAm은 friendQueue의 index를 뜻 한다.
이 계산은, 현재 인덱스에서 moves만큼 이동하며, wrap around 이므로, remains로 나눈 값을 사용한다.
5. friendQueue[whereIAm]을 제거한다.
6. friendQueue.first!를 반환한다. ( 1개 남을때 까지 반복했으므로 [0]외에는 없다. )
정답 코드
더보기
class Solution {
func findTheWinner(_ n: Int, _ k: Int) -> Int {
var friendQueue = Array(1...n)
var whereIAm = 0 // index of Queue
while friendQueue.count != 1 {
let remains = friendQueue.count
let moves = k - 1
whereIAm = (whereIAm + (moves)) % remains
print(friendQueue.remove(at: whereIAm))
}
return friendQueue.first!
}
}