C++ Easy to Understand


  • 11
    class Solution {
    public:
        vector<string> findRelativeRanks(vector<int>& nums) {
            priority_queue<pair<int,int> > pq;
            for(int i=0;i<nums.size();i++)
            {
                pq.push(make_pair(nums[i],i));
            }
            vector<string> res(nums.size(),"");
            int count = 1;
            for(int i=0; i<nums.size();i++)
            {
                if(count==1) {res[pq.top().second] = "Gold Medal"; count++;}
                else if(count==2) {res[pq.top().second] = "Silver Medal"; count++;}
                else if(count==3) {res[pq.top().second] = "Bronze Medal"; count++;}
                else {res[pq.top().second] = to_string(count); count++;}
                pq.pop();
            }
            return res;
        }
    };

  • 2

    I had the same idea.

        vector<string> findRelativeRanks(vector<int>& nums) {
            priority_queue<pair<int,int>> pq;
            for (int i=0, sz=nums.size();i<sz;i++)
                pq.push({nums[i], i});
            int count = 1;    
            vector<string> res(nums.size());
            while(pq.size()){
                auto p = pq.top();
                pq.pop();
                if (count==1)
                    res[p.second] = "Gold Medal";
                else if (count==2)
                    res[p.second] = "Silver Medal";
                else if (count==3)
                    res[p.second] = "Bronze Medal";
                else
                    res[p.second] = to_string(count);
                count++;
            }
            return res;
        }

  • 4
    D

    @sodhanipranav no need to use count, use the index i is more concise.

    for (int i=0; i<nums.size(); i++) {
        p = pq.top();
        pq.pop();
        if (i==0) rank[p.second] = "Gold Medal";
        else if (i==1) rank[p.second] = "Silver Medal";
        else if (i==2) rank[p.second] = "Bronze Medal";
        else rank[p.second] = to_string(i+1);
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.