넘치게 채우기

[LeetCode] 506. Relative Ranks 본문

PS/LeetCode

[LeetCode] 506. Relative Ranks

riveroverflow 2024. 5. 8. 10:53
728x90
반응형

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;
    }
};

 

728x90
반응형