506. 相对名次

优先队列

import java.util.Comparator;
import java.util.PriorityQueue;

class Solution {
    public String[] findRelativeRanks(int[] score) {

        /**
         * 使用优先队列从小到大存储分数,同时存储该分数原来的索引
         * 比较数组之间的大小必须要重写比较器,指定比较的目标
         */
        PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });

        /**
         * 先将分数存进优先队列
         */
        for (int i = 0; i < n; i++) {
            pq.add(new int[]{score[i], i});
        }

        int n = score.length;
        String[] res = new String[n];
        
        /**
         * 挨个取出优先队列的元素,如果是前三名要区别对待
         */
        while (!pq.isEmpty()){

            if (n == 1){
                res[pq.poll()[1]] = "Gold Medal";
            }
            else if (n == 2){
                res[pq.poll()[1]] = "Silver Medal";
            }
            else if (n == 3){
                res[pq.poll()[1]] = "Bronze Medal";
            }
            else {
                res[pq.poll()[1]] = Integer.toString(n);
            }

            n--;
        }

        return res;
    }
}

/**
 * 时间复杂度 O(nlogn)
 * 空间复杂度 O(n)
 */

集合

import java.util.TreeMap;

class Solution {
    public String[] findRelativeRanks(int[] score) {

        /**
         * 使用TreeMap存储分数和索引,分数作为键,从小到大排序
         */
        TreeMap<Integer, Integer> map = new TreeMap<>();
        String[] res = new String[score.length];

        for (int i = 0; i < score.length; i++) {
            map.put(score[i], i);
        }

        int n = score.length;

        for (int key : map.keySet()){

            if (n == 1){
                res[map.get(key)] = "Gold Medal";
            }
            else if (n == 2){
                res[map.get(key)] = "Silver Medal";
            }
            else if (n == 3){
                res[map.get(key)] = "Bronze Medal";
            }
            else {
                res[map.get(key)] = Integer.toString(n);
            }

            n--;
        }

        return res;
    }
}

/**
 * 时间复杂度 O(nlogn)
 * 空间复杂度 O(n)
 */

https://leetcode-cn.com/problems/relative-ranks/

posted @ 2021-11-01 21:58  振袖秋枫问红叶  阅读(41)  评论(0)    收藏  举报