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

转载于:https://www.cnblogs.com/panini/p/6649456.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值