3178. Find the Child Who Has the Ball After K Seconds
LeetCode
https://leetcode.com/problems/find-the-child-who-has-the-ball-after-k-seconds/
문제
- 두 개의 양의 정수 n과 k가 주어졌습니다.
- 0부터 n-1까지 번호가 매겨진 n명의 아이가 왼쪽에서 오른쪽으로 줄을 서 있습니다.
- 처음에는 0번 아이가 공을 갖고 있으며 매초 공을 오른쪽으로 전달합니다.
- 공이 줄의 양 끝에 도달하면 전달 방향이 반대로 바뀝니다.
- k초 후에 공을 받은 아이의 번호를 반환하는 코드를 작성하세요.
예제
- Input: n = 3, k = 5
- Output: 1
풀이 과정 #1
- 변수 i를 0부터 n-1까지 1씩 증가시키며 i를 리스트로 생성하여 변수 children에 저장합니다.
- children과 children의 첫 번째 요소와 마지막 요소를 제외한 부분을 반대로 뒤집어 합친 리스트를 변수 queue에 저장합니다.
- 주어진 정수 k를 queue의 길이로 나눈 나머지를 인덱스로 사용하여 queue의 해당 요소를 반환합니다.
코드(Python) #1
class Solution:
def numberOfChild(self, n: int, k: int) -> int:
children = [i for i in range(n)]
queue = children + children[1:-1][::-1]
return queue[k % len(queue)]
풀이 과정 #2
- 주어진 정수 k를 n-1로 나눈 몫과 나머지를 각각 변수 div와 mod에 저장합니다.
- div가 짝수이면 mod를 반환합니다.
- 그렇지 않으면 n-1-mod를 반환합니다.
코드(Python) #2
class Solution:
def numberOfChild(self, n: int, k: int) -> int:
div, mod = divmod(k, n-1)
if div % 2 == 0:
return mod
else:
return n - 1 - mod
참고
- divmod(a, b) : a를 b로 나눈 몫과 나머지를 튜플 형태로 반환
'알고리즘 스터디 > Python' 카테고리의 다른 글
| [LeetCode] 1385. Find the Distance Value Between Two Arrays (0) | 2024.09.12 |
|---|---|
| [LeetCode] 1331. Rank Transform of an Array (0) | 2024.09.12 |
| [LeetCode] 3280. Convert Date to Binary (0) | 2024.09.10 |
| [LeetCode] 1800. Maximum Ascending Subarray Sum (0) | 2024.09.09 |
| [LeetCode] 2119. A Number After a Double Reversal (0) | 2024.09.09 |