-
큐_LeetCode_find-the-winner-of-the-circular-game알고리즘/알고리즘 문제풀이 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! } }
'알고리즘 > 알고리즘 문제풀이' 카테고리의 다른 글
이진트리_LeetCode_binary-search (0) 2021.09.02 배열_LeetCode_Rotate Array (0) 2021.08.30 해쉬_Leetcode_rabbits-in-forest (0) 2021.08.25 DFS/BFS 백트랙킹_백준_15649 (0) 2021.08.24 정렬_LeetCode_Height Checker (0) 2021.08.23