12-2 506. 相对名次
作者:互联网
506. 相对名次
思路:哈希+排序
先复制一遍原数组并排序,通过哈希保存每个元素名次,最后遍历一遍原数组对应的名次放入 r e s res res中
时间复杂度: O ( n l o g n ) O(nlogn) O(nlogn) 排序
空间复杂度: O ( n ) O(n) O(n) 哈希表、复制数组
class Solution {
public:
vector<string> findRelativeRanks(vector<int>& score) {
vector<string> res;
unordered_map<int, string> hash;
vector<int> a = score;
sort(a.begin(), a.end());
string models[3] = {"Gold Medal", "Silver Medal", "Bronze Medal"};
for (int i = a.size() - 1; i >= 0; i -- ) {
int rank = a.size() - i;
if (rank <= 3)
hash[a[i]] = models[rank - 1];
else
hash[a[i]] = to_string(rank);
}
for (auto& t : score)
res.push_back(hash[t]);
return res;
}
};
标签:12,名次,res,vector,哈希,506,排序,Medal 来源: https://blog.csdn.net/MATLAB2020ab/article/details/121716996