//本文内容来自StarSight,欢迎访问。
本文的题目是一道基础题(506题),基于排序问题,借此熟悉一下快排和冒泡及其使用,同时也能很明显地看出快排的优势。
题目内容
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:
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.
我的思路
此问题基本就是个排序问题,当不能光排序,最后还需要给他们按未排序的数组分配名次。所以需要一个数组来建立排序后的位置与排序前的位置关系。即排序后的位置与原数组位置的信息丢失了,因此我们在排序的同时就需要保留这份信息。
冒泡排序实现
|
|
快速排序实现
|
|
再贴一张快排思路图,来自pzhtpf,但除了这幅图其他的讲的过于混乱。需要完整看快排算法可以看参考链接。

实现时遇到的问题
1.排序算法不够熟练,所以一开始用冒泡做。
2.如何存储关系不明确,也就是思路不够明晰,其实只用把numsTMp中的内容做一个交换(冒泡)或者直接给新位置赋上旧位置的值(快排)即可。
两种排序的运行时间对比
其实差距还是很明显的,快排大概能击败95%,冒泡则只有20%不到。
参考链接
原题链接:relative-ranks
快排实现:白话经典算法系列之六 快速排序 快速搞定