
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Relative Ranks in C++
Suppose we have a list of scores of N athletes, we have to find their relative ranks and the people with the top three highest scores, who will be different medals: "Gold", "Silver" and "Bronze".
So, if the input is like [2,5,3,1,0], then the output will be [Bronze,Gold,Silver,4,5]
To solve this, we will follow these steps −
-
if size of nums is same as 1, then −
return "Gold"
-
if size of nums is same as 2, then −
-
if nums[0] > nums[1], then −
return "Gold", "Silver"
-
Otherwise
return "Silver", "Gold"
-
Define an array v
DDefine an array vec
-
for initialize i := 0, when i < size of nums, update (increase i by 1), do −
insert nums[i] at the end of v
sort the array v
reverse the array v
Define one map mp
-
if size of nums > 2, then −
insert {v[0], "Gold" } into mp
insert {v[1], "Silver" } into mp
insert {v[2], "Bronze" } into mp
-
for initialize i := 3, when i < size of v, update (increase i by 1), do −
insert { v[i], i + 1 as string} into mp
-
for initialize i := 0, when i < size of nums, update (increase i by 1), do −
insert mp[nums[i]] at the end of vec
return vec
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: vector<string> findRelativeRanks(vector<int>& nums){ if (nums.size() == 1){ return { "Gold" }; } if (nums.size() == 2){ if (nums[0] > nums[1]) return { "Gold", "Silver" }; else return { "Silver", "Gold" }; } vector<int> v; vector<string> vec; for (int i = 0; i < nums.size(); i++) v.push_back(nums[i]); sort(v.begin(), v.end()); reverse(v.begin(), v.end()); map<int, string> mp; if (nums.size() > 2) { mp.insert({v[0], "Gold" }); mp.insert({v[1], "Silver" }); mp.insert({v[2], "Bronze" }); for (int i = 3; i < v.size(); i++) { mp.insert({ v[i], to_string(i + 1) }); } for (int i = 0; i < nums.size(); i++) vec.push_back(mp[nums[i]]); } return vec; } }; main(){ Solution ob; vector<int> v = {2,5,3,1,0}; print_vector(ob.findRelativeRanks(v)); }
Input
{2,5,3,1,0}
Output
[Bronze, Gold, Silver, 4, 5, ]