LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제
You are given an integer array score of size n, where score[i] is the score of the ith athlete in a competition. All the scores are guaranteed to be unique.
The athletes are placed based on their scores, where the 1st place athlete has the highest score, the 2nd place athlete has the 2nd highest score, and so on. The placement of each athlete determines their rank:
- The 1st place athlete's rank is "Gold Medal".
- The 2nd place athlete's rank is "Silver Medal".
- The 3rd place athlete's rank is "Bronze Medal".
- For the 4th place to the nth place athlete, their rank is their placement number (i.e., the xth place athlete's rank is "x").
Return an array answer of size n where answer[i] is the rank of the ith athlete.
Example 1:
Input: score = [5,4,3,2,1]
Output: ["Gold Medal","Silver Medal","Bronze Medal","4","5"]
Explanation: The placements are [1st, 2nd, 3rd, 4th, 5th].
Example 2:
Input: score = [10,3,8,9,4]
Output: ["Gold Medal","5","Bronze Medal","Silver Medal","4"]
Explanation: The placements are [1st, 5th, 3rd, 2nd, 4th].
Constraints:
- n == score.length
- 1 <= n <= 104
- 0 <= score[i] <= 106
- All the values in score are unique.
풀이
나의 풀이법
풀이 접근 과정
값은 unique 하다고 하니 score를 key로 갖고, 순위를 value로 갖는 map을 만들어 쓰면 되겠다고 생각했다.
최종 소스코드
class Solution {
fun findRelativeRanks(score: IntArray): Array<String> {
val answer = Array(score.size) { "" }
val map = hashMapOf<Int, Int>()
score.sortedByDescending { it }.forEachIndexed { idx, i ->
map[i] = idx + 1
}
score.forEachIndexed { idx, i ->
when (map[i]) {
1 -> answer[idx] = "Gold Medal"
2 -> answer[idx] = "Silver Medal"
3 -> answer[idx] = "Bronze Medal"
else -> answer[idx] = "${map[i]}"
}
}
return answer
}
}
score를 내림차순으로 정렬하여 해당 index를 value값으로 가지면서 score를 key로 갖는 map을 만든다.
map의 값에 맞춰 메달을 지정해주는 answer를 만들어 리턴해준다.
Comment
공간복잡도와 시간 복잡도가 모두 안좋게 나왔다.
그런데 내가 생각했을 때는 이게 최선인데…ㅠㅠ
'LeetCode > Kotlin | Easy' 카테고리의 다른 글
[LeetCode/Kotlin]Easy - 278. First Bad Version (0) | 2024.04.12 |
---|---|
[LeetCode/Kotlin]Easy - 1. Two Sum (0) | 2023.10.13 |
[LeetCode/Kotlin]Easy - 228. Summary Ranges (0) | 2023.09.19 |
[LeetCode/Kotlin]Easy - 704. Binary Search (0) | 2023.09.19 |
[LeetCode/Kotlin]Easy - 463. Island Perimeter (0) | 2023.09.14 |