嗯。。。写得也很丑,自己就是写得最笨的那种先新建排序,然后依次查找排序后位置来决定相对名次,感觉笨笨的,不知道能不能利用map按key值排序来做?看看别人怎么写得吧
自己的解法
class Solution {
public:
vector<string> findRelativeRanks(vector<int>& nums) {
vector<string> output;
vector<int> temp = nums;
vector<string> medal;
medal.push_back("Gold Medal");
medal.push_back("Silver Medal");
medal.push_back("Bronze Medal");
sort(temp.begin(), temp.end());
for (int i = 0; i < nums.size(); i ++){
int j = 0;
while (temp[j] != nums[i])
j++;
int k = nums.size() - j;
if (k <= 3){
output.push_back(medal[k-1]);
}else{
output.push_back(to_string(k));
}
}
return output;
}
};
人家的解法
看似类似的解法
挺重要的,注意理解vector的直接赋值。。。在这里不会耗费大量空间,与上次遇到的不同。写得比我好。
class Solution {
public:
vector<string> findRelativeRanks(vector<int>& nums) {
vector<int> rank;
for(int i=0; i<nums.size(); ++i) rank.push_back(i);
sort(rank.begin(), rank.end(), [&](int a, int b){return nums[a] > nums[b];});
vector<string> ranks(nums.size());
for(int i=3; i<nums.size(); ++i){
ranks[rank[i]] = std::to_string(i+1);
}
if(nums.size() > 0) ranks[rank[0]] = "Gold Medal";
if(nums.size() > 1) ranks[rank[1]] = "Silver Medal";
if(nums.size() > 2) ranks[rank[2]] = "Bronze Medal";
return ranks;
}
};
没遇到过的解法
神奇的priority_queue,以后好好看看是怎么用的。
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;
}
};
网友评论