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