본문 바로가기

Algorithm/자료구조

(C++) - LeetCode (easy) 1331. Rank Transform of an Array

반응형

https://leetcode.com/problems/rank-transform-of-an-array/description/

 

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

여러 자료구조를 사용해 푼 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

1. 더 큰 원소가 queue front에 오도록 priority_queue pq를 선언 후 arr의 원소를 삽입합니다2. pq의 원소가 key, rank가 value인 rankMap을 선언해줍니다3. 정답 변수 ans를 선언해줍니다.

📔 풀이과정

pq size가 있는 동안 while loop를 수행합니다.1. rankMap에 없는 원소라면 해당원소의 curRank를 넣고 증가시켜줍니다.2. arr의 원소를 순회하며 각 원소별 rank를 ans에 저장합니다.

📔 정답 출력 | 반환

ans를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    vector<int> arrayRankTransform(vector<int>& arr) {
        vector<int> rank;
        map<int,int> rankMap;
        priority_queue <int, vector<int>, greater<int>>pq;
        for(auto a : arr) {
            pq.push(a);
        }
        int curRank = 1;
        while(pq.size()) {
            if(!rankMap.contains(pq.top())) {
                rankMap[pq.top()] = curRank++;
            }
            pq.pop();
        }
        for(auto a : arr) {
            rank.push_back(rankMap[a]);
        }
        return rank;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.