今天做了大概四五道题,但觉着这道题是最值得分享的吧,Relative Ranks意思是相对排名问题,下面是题目具体内容,大家可以通过翻译试着做一下:
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.
这道题从题目抽象出来的信息大概就是给定一个整型数组,然后找出前三名的成绩,分别替换为金银铜牌英文单词,其他分别用相对名次代替并输出。刚看到这道题的时候感觉有点dp的意思吧,但我dp思想应用的还不是很熟练,所以朝着其他的方向去思考解决办法。静下心来想了一段时间终于想出来了,所以我觉着遇到一些没有头绪的算法题不要太浮躁,静下心来一定可以的,我们可以首先对数组进行排序,然后记录数组元素的的位置,然后根据排序再将数组元素替换为英文单词与相对排名输出即可,下面我给大家分享一下我自己的代码:
public String[] findRelativeRanks(int[] nums) {
String[] result = new String[nums.length];
int max = 0;
for (int i : nums) {
if (i > max) max = i;
}
int[] hash = new int[max + 1];
for (int i = 0; i < nums.length; i++) {
hash[nums[i]] = i + 1;
}
int place = 1;
for (int i = hash.length - 1; i >= 0; i--) {
if (hash[i] != 0) {
if (place == 1) {
result[hash[i] - 1] = "Gold Medal";
} else if (place == 2) {
result[hash[i] - 1] = "Silver Medal";
} else if (place == 3) {
result[hash[i] - 1] = "Bronze Medal";
} else {
result[hash[i] - 1] = String.valueOf(place);
}
place++;
}
}
return result;
}
这个代码的话挺好理解的,主要可能就是记录数据元素位置这一块需要另外创建一个数组去接收,可能会绕一点,但在经过一定的算法积累后,应该可以算是常规思想,当然解决问题的方法永远都不会只有一种,只有更优,没有最优,下面是我在社区看到的其他人的一个想法,思想其实差不多,只是它是将每个数组元素的位置都记录为了1,然后再逆序经过比较1位的数据元素下标由大到小输出,具体前三名的判断则也是创建一个计数器去比较,其余元素则根据计数器的判断输出相对排名即可,下面是另外一种实现的代码:
public String[] findRelativeRanks2(int[] nums) {
String[] s = new String[nums.length];
int flag = 1;
int max = nums[0];
for (int i = 0; i < nums.length; i++)
if (nums[i] > max)
max = nums[i];
int[] sup = new int[max + 1];
for (int i = 0; i < sup.length; i++)
sup[i] = 0;
for (int i = 0; i < nums.length; i++)
sup[nums[i]] = 1;
for (int i = sup.length - 1; i >= 0; i--) {
if (sup[i] == 1) {
for (int j = 0; j < nums.length; j++)
if (nums[j] == i)
s[j] = Integer.toString(flag);
flag++;
}
}
for (int i = 0; i < s.length; i++)
if (s[i].equals("1"))
s[i] = "Gold Medal";
else if (s[i].equals("2"))
s[i] = "Silver Medal";
else if (s[i].equals("3"))
s[i] = "Bronze Medal";
return s;
}
我觉着呢,这两种实现是比较类似的,至此我应该解析的较为清楚了,但在我快要结束这道题的思考时,脑子里突然闪过一个类HashMap呐,既然要存储数组元素的相对排名位置,为什么不用HashMap通过键值对记录数组元素的下标与相应位置的值呢,想到这里也发现了自己的一个不足,就是可能对一些集合类的应用不够熟练吧,如HashMap集合在数组中的经典应用,在思考问题、尤其是实现抽象算法时更应该拓宽一下思维,或者说我们可以试着先想一下自己学过的某些知识,譬如集合类、堆栈什么的,这有时候可能给我们提供一些解题思路,甚至给予我们算法上的很大优化。好啦、大概就是这样子的,学习生活中呢,我们要学会怎样去巧学妙学,应该有一种正确的适合自己的学习方法,这里我就不给大家提供Map实现,大家可以试着思考尝试一下怎样去实现~