leetcode506. Relative Ranks

題目要求

Given scores ofNathletes, 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".java

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

Note:code

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

現有N名運動員的成績,用一個正整數數組來表示,已知該正整數數組中的成績均惟一。要求用一個String數組返回對應下標上運動員的相對排名,其中前三名分別標記爲"Gold Medal", "Silver Medal"和"Bronze Medal",其它則用數字表示排名。排序

思路和代碼

這題直觀的來看能夠用排序得出運動員從高到低的得分,可是這樣就丟失了分數原來的下標。所以,假如咱們能夠將0-n這n個數字進行排序,排序的標準爲對應的運動員的成績。再根據下標將排序結果依次寫會。three

過程以下:get

假如一組運動員成績爲[1,3,2,5,4]
對應的下標爲[0,1,2,3,4]
則對第二個數組按照其對應的成績由低到高的排序結果爲[3,4,1,2,0]
再根據這個結果依次將結果寫入String數組中,
result[3]="Gold Medal", result[4]="Silver Medal", result[1]="Bronze Medal" result[2]="4" result[0]="5"

代碼以下:it

public String[] findRelativeRanks(int[] nums) {
       if (nums.length == 0) return new String[0];
       Integer[] indexes = Stream.iterate(0, i -> i+1).limit(nums.length).sorted(new Comparator<Integer>() {
           @Override
           public int compare(Integer o1, Integer o2) {
               return nums[o2] - nums[o1];
           }
       }).toArray(Integer[]::new);

       String[] result = new String[nums.length];
       for (int i = 0 ; i<indexes.length ; i++) {
           if (i == 0) {
               result[indexes[i]] = "Gold Medal";
           } else if (i == 1) {
               result[indexes[i]] = "Silver Medal";
           } else if (i == 2) {
               result[indexes[i]] = "Bronze Medal";
           } else {
               result[indexes[i]] = String.valueOf(i+1);
           }
       }
       return result;
   }

這裏使用了JAVA內置的排序,也可使用桶排序來下降時間複雜度。io

public String[] findRelativeRanks(int[] nums) {
       if (nums.length == 0) return new String[0];
       int maxValue = IntStream.of(nums).max().getAsInt();

       int[] buckets = new int[maxValue+1];
       for (int i = 0 ; i<nums.length ; i++) {
           buckets[nums[i]] = i+1;
       }

       int place = 1;
       String[] result = new String[nums.length];
       for (int i = buckets.length-1 ; i>=0 ; i--) {
           if (buckets[i] == 0) continue;
           if (place <= 3) {
               if (place == 1) {
                   result[buckets[i]-1] = "Gold Medal";
               } else if (place == 2) {
                   result[buckets[i]-1] = "Silver Medal";
               } else {
                   result[buckets[i]-1] = "Bronze Medal";
               }
           } else {
               result[buckets[i]-1] = String.valueOf(place);
           }
           place++;
       }
       return result;
   }
相關文章
相關標籤/搜索