首页 > 解决方案 > 哈希表:赎金票据 - Swift 中的黑客排名超时

问题描述

我的代码没问题,但在一些测试用例上会抽出时间,有什么改进的技巧吗?我的猜测是 indexOf 函数耗时太长。

func checkMagazine(magazine: [String], note: [String]) -> Void {
var mutableMag = magazine
if note.count > mutableMag.count {
    print("No")
    return
}
for word in note {
    if let index = mutableMag.index(of: word) {
        mutableMag.remove(at: index)
    } else {
        print("No")
        return
    }
}
print("Yes") }

请在此链接中找到挑战:https ://www.hackerrank.com/challenges/ctci-ransom-note/problem

标签: arraysswiftdictionaryswift3hashmap

解决方案


通过所有测试的一种可能的解决方案是使用NSCountedSet将单词存储在便笺和杂志中,并将每个单词note的计数与该单词的计数进行比较magazine,如果其中任何一个较低magazine,则提前返回并打印No

我还建议更改函数签名以返回一个Bool值,即使黑客等级生成的函数原型返回Void。最好是做checkMagazine一个纯函数,不要在里面做任何I/O操作。

func checkMagazine(magazine: [String], note: [String]) -> Bool {
    let magazineWords = NSCountedSet(array: magazine)
    let noteWords = NSCountedSet(array: note)
    for noteWord in noteWords {
        if magazineWords.count(for: noteWord) < noteWords.count(for: noteWord) {
            return false
        }
    }
    return true
}

然后你只需要将生成的代码的末尾更改为以下内容:

let magazineWorks = checkMagazine(magazine: magazine, note: note)
if magazineWorks {
    print("Yes")
} else {
    print("No")
}

推荐阅读