go語(yǔ)言題解LeetCode506相對(duì)名次示例詳解
一 描述
給你一個(gè)長(zhǎng)度為 n 的整數(shù)數(shù)組 score ,其中 score[i] 是第 i 位運(yùn)動(dòng)員在比賽中的得分。所有得分都 互不相同 。
運(yùn)動(dòng)員將根據(jù)得分 決定名次 ,其中名次第 1 的運(yùn)動(dòng)員得分最高,名次第 2 的運(yùn)動(dòng)員得分第 2 高,依此類推。運(yùn)動(dòng)員的名次決定了他們的獲獎(jiǎng)情況:
- 名次第 1 的運(yùn)動(dòng)員獲金牌 "Gold Medal" 。
- 名次第 2 的運(yùn)動(dòng)員獲銀牌 "Silver Medal" 。
- 名次第 3 的運(yùn)動(dòng)員獲銅牌 "Bronze Medal" 。
- 從名次第 4 到第 n 的運(yùn)動(dòng)員,只能獲得他們的名次編號(hào)(即,名次第 x 的運(yùn)動(dòng)員獲得編號(hào) "x")。
使用長(zhǎng)度為 n 的數(shù)組 answer 返回獲獎(jiǎng),其中 answer[i] 是第 i 位運(yùn)動(dòng)員的獲獎(jiǎng)情況。
示例 1:
輸入:score = [5,4,3,2,1] 輸出:["Gold Medal","Silver Medal","Bronze Medal","4","5"] 解釋:名次為 [1st, 2nd, 3rd, 4th, 5th] 。
示例 2:
輸入:score = [10,3,8,9,4] 輸出:["Gold Medal","5","Bronze Medal","Silver Medal","4"] 解釋:名次為 [1st, 5th, 3rd, 2nd, 4th] 。
提示:
n == score.length
1 <= n <= 10^4
0 <= score[i] <= 10^6
score 中的所有值 互不相同
二 分析
本題以map映射求解,首先把所有的字符串分別添加到指定map集合中去,并依次給予對(duì)應(yīng)的索引,隨后對(duì)字符串?dāng)?shù)組進(jìn)行從大到小排序,并依次從map集合中由鍵找值,并把該值給到提前創(chuàng)建的字符串?dāng)?shù)組中作為索引,從大到小依次賦予“Gold Medal”、“Silver Medal”、“Bronze Medal”以及3、4、5...
三 答案
class Solution {
public String[] findRelativeRanks(int[] nums) {
if(nums.length==1) {
return new String[]{"Gold Medal"};
}
String[] arr = new String[nums.length];
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
int count = 0;
for(int i = 0,j=0;i<nums.length && j<nums.length;i++,j++) {
map.put(nums[i],j);
}
Arrays.sort(nums);
for(int i = 0;i<nums.length/2;i++) {
int temp = nums[nums.length-i-1];
nums[nums.length-i-1] = nums[i];
nums[i] = temp;
}
if(nums.length==2) {
arr[map.get(nums[0])] = "Gold Medal";
arr[map.get(nums[1])] = "Silver Medal";
return arr;
}
arr[map.get(nums[0])] = "Gold Medal";
arr[map.get(nums[1])] = "Silver Medal";
arr[map.get(nums[2])] = "Bronze Medal";
for(int i = 3;i<nums.length;i++) {
arr[map.get(nums[i])] = i+1+"";
}
return arr;
}
}以上就是go語(yǔ)言題解LeetCode506相對(duì)名次示例詳解的詳細(xì)內(nèi)容,更多關(guān)于go語(yǔ)言題解相對(duì)名次的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
go使用SQLX操作MySQL數(shù)據(jù)庫(kù)的教程詳解
sqlx 是 Go 語(yǔ)言中一個(gè)流行的操作數(shù)據(jù)庫(kù)的第三方包,它提供了對(duì) Go 標(biāo)準(zhǔn)庫(kù) database/sql 的擴(kuò)展,簡(jiǎn)化了操作數(shù)據(jù)庫(kù)的步驟,下面我們就來(lái)學(xué)習(xí)一下go如何使用SQLX實(shí)現(xiàn)MySQL數(shù)據(jù)庫(kù)的一些基本操作吧2023-11-11
詳解Go語(yǔ)言Sync.Pool為何不加鎖也能夠?qū)崿F(xiàn)線程安全
在這篇文章中,我們將剖析sync.Pool內(nèi)部實(shí)現(xiàn)中,介紹了sync.Pool比較巧妙的內(nèi)部設(shè)計(jì)思路以及其實(shí)現(xiàn)方式。在這個(gè)過(guò)程中,也間接介紹了為何不加鎖也能夠?qū)崿F(xiàn)線程安全,感興趣的可以學(xué)習(xí)一下2023-04-04
golang實(shí)現(xiàn)mysql數(shù)據(jù)庫(kù)事務(wù)的提交與回滾
這篇文章主要介紹了golang實(shí)現(xiàn)mysql數(shù)據(jù)庫(kù)事務(wù)的提交與回滾,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-04-04

