https://leetcode.com/problems/relative-ranks/description/
Solution 1. Lambda expression.
vector<string> findRelativeRanks(vector<int>& nums) {
int N = nums.size();
if(N==0) return vector<string> {};
vector<int> rank2idx(N);
vector<string> res(N);
for(int i=0; i < N; i++) rank2idx[i] = i;
sort(rank2idx.begin(), rank2idx.end(), [&](int i, int j){return nums[i]>nums[j];});
for(int i=3; i < N; i++) {
res[rank2idx[i]] = to_string(i+1);
}
if(N>0) res[rank2idx[0]] = "Gold Medal";
if(N>1) res[rank2idx[1]] = "Silver Medal";
if(N>2) res[rank2idx[2]] = "Bronze Medal";
return res;
}
Solution 2. Using a map.
vector<string> findRelativeRanks(vector<int>& nums) {
map<int, int, greater<int>> score2idx;
vector<string> res(nums.size());
for(int i=0;i<nums.size();i++){
score2idx[nums[i]] = i;
}
int i=1;
for(auto &x: score2idx) {
if(i==1) res[x.second] = "Gold Medal";
else if(i==2) res[x.second] = "Silver Medal";
else if(i==3) res[x.second] = "Bronze Medal";
else res[x.second] = to_string(i);
i++;
}
return res;
}
Solution 3. Use a priority_queue
vector<string> findRelativeRanks(vector<int>& nums) {
priority_queue<pair<int,int>> q;
vector<string> res(nums.size());
for(int i=0;i<nums.size();i++){
q.push(make_pair(nums[i],i));
}
for(int i=0; i<nums.size();i++) {
auto x = q.top();
if(i==0) res[x.second] = "Gold Medal";
else if(i==1) res[x.second] = "Silver Medal";
else if(i==2) res[x.second] = "Bronze Medal";
else res[x.second] = to_string(i+1);
q.pop();
}
return res;
}
No comments:
Post a Comment