IOS 算法(基础篇) ----- 相对名次

2021-12-02  本文已影响0人  ShawnAlex

给你一个长度为 n 的整数数组 score ,其中 score[i] 是第 i 位运动员在比赛中的得分。所有得分都 互不相同 。运动员将根据得分 决定名次 ,其中名次第 1 的运动员得分最高,名次第 2 的运动员得分第 2 高,依此类推。运动员的名次决定了他们的获奖情况:
名次第 1 的运动员获金牌 "Gold Medal" 。
名次第 2 的运动员获银牌 "Silver Medal" 。
名次第 3 的运动员获铜牌 "Bronze Medal" 。
从名次第 4 到第 n 的运动员,只能获得他们的名次编号(即,名次第 x 的运动员获得编号 "x")。
使用长度为 n 的数组 answer 返回获奖,其中 answer[i] 是第 i 位运动员的获奖情况。
n == score.length
1 <= n <= 104
0 <= score[i] <= 106
score 中的所有值 互不相同

题目稍微解释下, 其实就是处理一个分数数组, 分数由大到小

用哈希法以分数做key, 排名做value 维护哈希表,(一对对键值对 key-value, 无序的)
以 score = [10,3,8,9,4] 举例, 形成的哈希表为
[
3: "5",
8: "Bronze Medal",
9: "Silver Medal",
4: "4",
10: "Gold Medal"
]

再遍历score按哈希表返回即可

未翻译版

    func findRelativeRanks(_ score: [Int]) -> [String] {

        var res = [String](), dic = [Int:String]()
        let temp = score.sorted(by: >), a = ["Gold Medal", "Silver Medal", "Bronze Medal"]
        
        for i in 0..<temp.count {
            
            if (i < 3) {
                dic[temp[i]] = a[i]
                continue
            }
            
            dic[temp[i]] = String(i + 1)
        }
        
        for i in score {
            res.append(dic[i]!)
        }
        
        return res;

    }

翻译版

    func findRelativeRanks(_ score: [Int]) -> [String] {

        // 定义返回结果res, 哈希表dic
        var res = [String](), dic = [Int:String]()
        // 定义temp为倒序数组, a 为前三个字符串
        let temp = score.sorted(by: >), a = ["Gold Medal", "Silver Medal", "Bronze Medal"]
        
        // 遍历倒序数组temp
        for i in 0..<temp.count {
            
            // 以 [分数:排名] 做哈希表
            if (i < 3) {
                dic[temp[i]] = a[i]
                continue
            }
            
            dic[temp[i]] = String(i + 1)
        }
        
        // 遍历score 按表返回
        for i in score {
            res.append(dic[i]!)
        }
        
        // 返回结果
        return res;

    }

精简版

利用swift自带函数优化下代码

    func findRelativeRanks(_ score: [Int]) -> [String] {
        let temp = score.sorted(by: >), 
            a = ["Gold Medal", "Silver Medal", "Bronze Medal"]
        var dic = [Int:String]()
        for (i, score) in temp.enumerated() {   
            if (i < 3) {
                dic[score] = a[i]
                continue
            }
            dic[score] = String(i + 1)
        }
        return score.map{ dic[$0]! }

    }

题目来源:力扣(LeetCode) 感谢力扣爸爸 :)
IOS 算法合集地址

上一篇 下一篇

猜你喜欢

热点阅读