解题思路
map底层实现是一棵红黑树,按照key值升序排列,题目给出分数各自不同
分情况讨论:
- n=1:这个人就是金牌
- n=2:两个人比较一下得出金银牌
- n>=3
- 用一个
map<int,int>temp
来存放分数和下标值(下标值代表第几位)。根据排序的结果从第1到n-3位的名次就是他们分数的名次,我们已知map是升序排列,因此在map中的第一位名次是n,以此类推。 - 在map中的最后三位分别是金银铜牌。
map查找的时间复杂度是O(logn),最终的时间复杂度是O(n*logn)
代码
class Solution {
public:
vector<string> findRelativeRanks(vector<int>& score) {
int n=score.size();
vector<string>answer(n);
if(n==1){answer[0]="Gold Medal";return answer;}
if(n==2)
{
answer[0]=score[0]>score[1]?"Gold Medal":"Silver Medal";
answer[1]=score[0]<score[1]?"Gold Medal":"Silver Medal";
return answer;
}
//n>=3的情况
map<int,int>temp;
for(int i=0;i<n;i++){temp[score[i]]=i;}//关键字是分数,i是第几位
auto it=temp.begin();//it->first is score,it->second是原数组的标号
for(int i=0;i<n-3;it++,i++){answer[it->second]=to_string(n-i);}
//最后三位分别为金银铜牌
answer[it->second]="Bronze Medal";it++;
answer[it->second]="Silver Medal";it++;
answer[it->second]="Gold Medal";
return answer;
}
};