力扣训练9

506相对名次

把原数据复制一遍再排序,用map把数值和排名一一对应,注意to_string

class Solution {
public:
    vector<string> findRelativeRanks(vector<int>& score) {
        
        const string str[3]={"Gold Medal","Silver Medal","Bronze Medal"};
        vector<string> result;
        vector<int>score1(score);
        sort(score1.begin(),score1.end(),greater<int>());
        map<int,string>map1;
        int con=3;
        for(int i=0;i<score.size();i++)
        {
            if(i<3)
            {
                map1[score1[i]]=str[i];
            }
            else
            {
                map1[score1[i]]=to_string(++con);

            }
        }
        for(auto e:score)
        {
            result.push_back(map1[e]);
        }
        return result;

    }
};

703数据流中的第 K 大元素

优先队列

class KthLargest {
private:
    priority_queue<int, vector<int>, greater<>> pq;
    int sz;
public:
    KthLargest(int k, vector<int>& nums) : sz(k) {
        for (auto& num : nums) {
            pq.emplace(num);
            if (pq.size() > sz) pq.pop();
        }
    }

    int add(int val) {
        pq.emplace(val);
        if (pq.size() > sz) pq.pop();
        return pq.top();
    }
};

264丑数2

先存再排

class Solution {
public:
    int nthUglyNumber(int n) {
        long ans = 1;
        priority_queue<long, vector<long>, greater<long>> smallQ;
        for (int i = 1; i < n; i++) {
            smallQ.push(ans * 2);
            smallQ.push(ans * 3);
            smallQ.push(ans * 5);

            ans = smallQ.top();
            smallQ.pop();

            while (smallQ.top() == ans) {
                smallQ.pop();
            }
        }
        return ans;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值