506. 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.

 

Note:

  1. N is a positive integer and won't exceed 10,000.
  2. All the scores of athletes are guaranteed to be unique.

链接:https://leetcode.com/problems/relative-ranks/#/description

3/30/2017

beat 41%, 32ms

注意:

1. 初始化PQ,特别是逆序

2. PQ.toArray()返回的是Object[],若要变成其他类型需要遍历赋值

3. binarySearch要逆序查找,也要传入Collections.reverseOrder()

4. 第19行需要index + 1

5. 自己没有想到一次遍历或者是O(n)算法

 1 public class Solution {
 2     public String[] findRelativeRanks(int[] nums) {
 3         String[] ret = new String[nums.length];
 4         PriorityQueue<Integer> p = new PriorityQueue<Integer>(nums.length, Collections.reverseOrder());
 5 
 6         for (int i = 0; i < nums.length; i++) {
 7             p.add(nums[i]);
 8         }
 9 
10         Integer[] a = new Integer[nums.length];
11         for (int i = 0; i < nums.length; i++) {
12             a[i] = p.poll();
13         }
14         for (int i = 0; i < nums.length; i++) {
15             int index = Arrays.binarySearch(a, nums[i], Collections.reverseOrder());
16             if (index == 0) ret[i] = "Gold Medal";
17             else if (index == 1) ret[i] = "Silver Medal";
18             else if (index == 2) ret[i] = "Bronze Medal";
19             else ret[i] = Integer.toString(index + 1);
20         }
21         return ret;
22     }
23 }

别人的算法,可以用排序而不用priorityqueue,但是时间复杂度和空间复杂度没有什么大变化

https://discuss.leetcode.com/topic/77876/easy-java-solution-sorting/2

看起来大家并没有O(n)的解法,Python

https://discuss.leetcode.com/topic/77943/python-solution

更多讨论:

https://discuss.leetcode.com/category/655/relative-ranks

posted @ 2017-03-31 06:50  panini  阅读(286)  评论(0编辑  收藏  举报