zoukankan      html  css  js  c++  java
  • LeetCode Relative Ranks

    原题链接在这里:https://leetcode.com/problems/relative-ranks/#/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 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.

    题解:

    把nums sort同时要保留index信息. 按照index给result的对应index赋值.

    Time Complexity: O(nlogn), n = nums.length. Space: O(n).

    AC Java:

     1 public class Solution {
     2     public String[] findRelativeRanks(int[] nums) {
     3         int [][] pair = new int[nums.length][2];
     4         for(int i = 0; i<nums.length; i++){
     5             pair[i][0] = nums[i];
     6             pair[i][1] = i;
     7         }
     8         
     9         Arrays.sort(pair, (a, b)->(b[0]-a[0]));
    10         String [] res = new String[nums.length];
    11         for(int i = 0; i<nums.length; i++){
    12             if(i == 0){
    13                 res[pair[i][1]] = "Gold Medal";
    14             }else if(i == 1){
    15                 res[pair[i][1]] = "Silver Medal";
    16             }else if(i == 2){
    17                 res[pair[i][1]] = "Bronze Medal";
    18             }else{
    19                 res[pair[i][1]] = String.valueOf(i+1); 
    20             }
    21         }
    22         return res;
    23     }
    24 }
  • 相关阅读:
    20.logging模块
    21.django中间件源码阅读
    18.configparser模块
    15.DRF学习以及相关源码阅读
    19.tcp_upd
    13.关于继承封装,以及反射
    16.html转pdf的一个小示例
    14.django返回展示一张图片
    GridView列标题修改
    ~为服务器端根目录符
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/6649476.html
Copyright © 2011-2022 走看看