vector<pair<int, int>>或者有序map
功能相同
1 static bool sortPair(pair<int, int> a, pair<int, int> b) { 2 return a.second > b.second; 3 } 4 vector<string> findRelativeRanks(vector<int> &score) { 5 vector<string> res(score.size()); 6 7 vector<pair<int, int>> pairr; 8 9 for (int i = 0; i < score.size(); i++) { 10 pairr.push_back(pair<int, int>(i, score[i])); 11 } 12 13 sort(pairr.begin(), pairr.end(), sortPair); 14 for (int i = 0; i < pairr.size(); i++) { 15 switch (i) { 16 case 0: 17 res[pairr[i].first] = "Gold Medal"; 18 break; 19 case 1: 20 res[pairr[i].first] = "Silver Medal"; 21 break; 22 case 2: 23 res[pairr[i].first] = "Bronze Medal"; 24 break; 25 default: 26 res[pairr[i].first] = to_string(i + 1); 27 break; 28 } 29 } 30 return res; 31 }
1 vector<string> findRelativeRanks(vector<int>& score) { 2 int n=score.size(); 3 map<int,int,greater<int>>num2index; 4 for(int i=0;i<n;i++)num2index[score[i]]=i; 5 vector<string>ans(n); 6 int i=0; 7 for(auto mPair:num2index){ 8 int index=mPair.second; 9 if(i==0){ 10 ans[index]="Gold Medal"; 11 }else if(i==1){ 12 ans[index]="Silver Medal"; 13 }else if(i==2){ 14 ans[index]="Bronze Medal"; 15 }else ans[index]+=to_string(i+1); 16 i++; 17 } 18 return ans; 19 }