(算法分析Week13)Relative Ranks[Easy]
来源:互联网 发布:马云在贵州大数据 编辑:程序博客网 时间:2024/05/27 09:48
506. Relative Ranks[Easy]
题目来源
Description
Given scores of N athletes, find their relative ranks and the people with the top three highest scores, who will be awarded medals: “Gold Medal”, “Silver Medal” and “Bronze Medal”.
Example 1:
Input: [5, 4, 3, 2, 1]Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]Explanation: The first three athletes got the top three highest scores, so they got "Gold Medal", "Silver Medal" and "Bronze Medal". For the left two athletes, you just need to output their relative ranks according to their scores.
Note:
N is a positive integer and won’t exceed 10,000.
All the scores of athletes are guaranteed to be unique.
Solution
一开始没理解题目,直接一个排序然后按顺序名次123,发现WA。然后看测例,发现是按照输入顺序对应输出相应的名次。C++可以直接用优先队列排序,用一对数存对应的分数和出现的位置,即make_pair(nums[i],i)
每次取优先队列的第一个,赋值当前名次,加入返回的vector即可。
Complexity analysis
O(n)
Code
class Solution {public: string trans(int x) { ostringstream stream; stream<<x; return stream.str(); } vector<string> findRelativeRanks(vector<int>& nums) { priority_queue<pair<int, int>> que; for (int i = 0; i < nums.size(); i++) { que.push(make_pair(nums[i],i)); } vector<string> result(nums.size(), ""); //记得初始化 int count = 1; for (int i = 0; i < nums.size(); i++) { if (count == 1) { result[que.top().second] = "Gold Medal"; count++; } else if (count == 2) { result[que.top().second] = "Silver Medal"; count++; } else if (count == 3) { result[que.top().second] = "Bronze Medal"; count++; } else { result[que.top().second] = trans(count); count++; } que.pop(); } return result; }};
Result
阅读全文
0 0
- (算法分析Week13)Relative Ranks[Easy]
- leetcode 506. Relative Ranks(easy)
- Relative Ranks
- Relative Ranks
- Relative Ranks
- Relative Ranks
- Relative Ranks
- (算法分析Week13)Is Subsequence[Medium]
- (算法分析Week13)Combination Sum IV[Medium]
- 506. Relative Ranks
- LeetCode 506. Relative Ranks
- leetcode-506-Relative Ranks
- leetcode506: Relative Ranks
- 506. Relative Ranks
- 506. Relative Ranks
- 506. Relative Ranks
- 506. Relative Ranks (E)
- [Leetcode] 506. Relative Ranks
- 运用并查集与最小堆实现Kruskal算法
- MCMC和贝叶斯统计在宇宙微波背景辐射(CMB)中应用
- ZOJ 3471 Most Powerful 状压dp
- three.js中正交和透视投影相机的应用
- javascript关系运算符与逻辑运算符
- (算法分析Week13)Relative Ranks[Easy]
- Javascript中transducer的应用
- Spring官网jar包下载方法
- Logcat五种级别日志
- AI 技术与伦理
- PAT
- 堆栈(stack)的四种类型
- 更新一下进度。。
- c语言背后的汇编