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 }
  • 相关阅读:
    单位
    北京户口
    中科院助理工程师
    SQL学习
    question
    ROI选取过程
    IT学习网站
    撞库 拖库
    善用人类记忆的特点去高效学习
    为什么散步对健康很有益处
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/6649476.html
Copyright © 2011-2022 走看看