首页 文章

哈希表:赎金注 - 黑客在Swift超时中排名

提问于
浏览
0

我的代码没问题但是在一些测试用例上有时间,有任何改进的提示吗?我的猜测是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

1 回答

  • 1

    通过所有测试的一种可能解决方案是使用 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")
    }
    

相关问题