题目
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:
- N is a positive integer and won't exceed 10,000.
- All the scores of athletes are guaranteed to be unique.
解题思路
- 复制nums到一个新数组numsSort,进行逆序排序,则新字符串对应的rank即为Gold Medal Silver Medal Bronze Medal 4 5 ...
- 建立一个map,存储score和rank的对应关系
- 按照nums的顺序,将rank append到结果数组中
注意
数组‘=’赋值的是地址
考虑边界情况
- 输入数组大小为0,输出为空
- 输入数组大小为1,输出为[]string{"Gold Medal"}
代码
findRelativeRanks.go
package _506_Relative_Ranks
import (
"sort"
"strconv"
"fmt"
)
type IntSlice []int
func (s IntSlice) Len() int { return len(s) }
func (s IntSlice) Swap(i, j int){ s[i], s[j] = s[j], s[i] }
func (s IntSlice) Less(i, j int) bool { return s[i] > s[j] }
func FindRelativeRanks(nums []int) []string {
len1 := len(nums)
if 0 == len1 {
return []string{}
}else if 1 == len1{
return []string{"Gold Medal"}
}
var rank []string
var numsSorted []int
numsSorted = make([]int , 0, len1)
for _, v := range nums {
numsSorted = append(numsSorted, v)
}
sort.Sort(IntSlice(numsSorted))
fmt.Printf("sort:%+v\n", numsSorted)
fmt.Printf("nums:%+v\n", nums)
var rankMap map[int]string
rankMap = make(map[int]string)
if len1 >= 2 {
rankMap[numsSorted[0]] = "Gold Medal"
rankMap[numsSorted[1]] = "Silver Medal"
}
if len1 >= 3 {
rankMap[numsSorted[2]] = "Bronze Medal"
for i := 3; i < len1; i++ {
rankMap[numsSorted[i]] = strconv.Itoa(i+1)
}
}
fmt.Printf("rankMap:%+v\n", rankMap)
for i := 0; i < len1; i++ {
rank = append(rank, rankMap[nums[i]])
}
return rank
}
测试
findRelativeRanks_test.go
package _506_Relative_Ranks
import "testing"
func TestFindRelativeRanks(t *testing.T) {
var tests = []struct{
input []int
output []string
}{
{[]int{10,3,8,9,4}, []string{"Gold Medal","5","Bronze Medal","Silver Medal","4"}},
{[]int{}, []string{}},
{[]int{3}, []string{"Gold Medal"}},
{[]int{3, 2, 1}, []string{"Gold Medal","Silver Medal","Bronze Medal"}},
{[]int{5,4,3,2,1}, []string{"Gold Medal","Silver Medal","Bronze Medal","4","5"}},
}
for _, test := range tests {
ret := FindRelativeRanks(test.input)
t.Logf("want:%+v\n, get:%+v\n", test.output, ret)
}
}