넘치게 채우기
[LeetCode] 506. Relative Ranks 본문
https://leetcode.com/problems/relative-ranks/description/
leetcode - Relative Ranks
문제 유형 : 우선순위 큐
문제 난이도 : Easy
문제
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.
운동 경기 결과로 n개의 점수를 받습니다.
answer배열에는 score에 해당하는 선수의 인덱스에 1등은 "Gold Medal", 2등은 "Silver Medal", 3등은 "Bronze Medal"이라고 기록해야 합니다.
4등부터는 등수를 기록하면 됩니다.
풀이
우선순위 큐에 <점수, 인덱스> 형태로 저장시키고,
높은 점수가 우선이 되도록 합니다.
우선순위 큐에서 요소를 제거하면서, 첫 1,2,3은 메달을 할당하고, 나머지는 등수를 매기면 됩니다.
코드
C++
struct comp {
bool operator()(const auto &a, const auto &b){
return a.first < b.first;
};
};
class Solution {
public:
vector<string> findRelativeRanks(vector<int>& score) {
int n = score.size();
priority_queue<pair<int, int>, vector<pair<int, int>>, comp> pq;
vector<string> ans(n);
for(int i = 0; i < n; i++) {
pq.push({score[i], i});
}
int cnt = 0;
while(!pq.empty()) {
auto curr = pq.top();
pq.pop();
if(cnt >= 3) {
ans[curr.second] = to_string(cnt+1);
} else if (cnt == 2) {
ans[curr.second] = "Bronze Medal";
} else if (cnt == 1) {
ans[curr.second] = "Silver Medal";
} else {
ans[curr.second] = "Gold Medal";
}
cnt++;
}
return ans;
}
};
'PS > LeetCode' 카테고리의 다른 글
[LeetCode] 786. K-th Smallest Prime Fraction (0) | 2024.05.10 |
---|---|
[LeetCode] 3075. Maximize Happiness of Selected Children (0) | 2024.05.09 |
[LeetCode] 2816. Double a Number Represented as a Linked List (0) | 2024.05.07 |
[LeetCode] 2487. Remove Nodes From Linked List (0) | 2024.05.06 |
[LeetCode] 237. Delete Node in a Linked List (0) | 2024.05.05 |