Find the Winner of the Circular Game

Sett·2021년 8월 31일
0

문제

https://leetcode.com/problems/find-the-winner-of-the-circular-game/

문제 접근

  1. 배열로 만들어서
  2. 배열의 인덱스 k만큼 +1 하다가
  3. 도중에 배열의 count를 넘으면, 0으로 초기화
  4. [1,2,3,6] 여기서 6을 지운 경우, 0으로 초기화

소스 코드

func findTheWinner(_ n: Int, _ k: Int) -> Int {
    var arr: [Int] = []
    var index: Int = 0
    for i in 0..<n {
        arr.append(i+1)
    }
    while (arr.count != 1) {
        for _ in 0..<k - 1 {
            if index >= arr.count - 1 {
                index = 0
                continue
            }
            index += 1
        }
        arr.remove(at: index)
        if index > arr.count - 1 {
            index = 0
        }
    }
    return arr[0]
}
profile
안녕하세요

0개의 댓글

관련 채용 정보