arrays - 哈希表:赎金票据 - 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
解决方案
通过所有测试的一种可能的解决方案是使用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")
}
推荐阅读
- python - Pandas - 返回一行时如何排除空白单元格
- ios - 为什么应用程序在尝试加载我的 nib 文件时崩溃?
- c++ - C++ 变量列表初始化
- javascript - 我的函数在尝试渲染图像时返回一个承诺
- javascript - 页面加载时如何显示模式
- python - 为什么我的摩尔斯电码解码工具找不到任何后续字符?
- sql - 为什么 Hive 在使用按日期排序时会抛出错误?
- python - 是否有查找一个 netCDF 文件的最后一个时间戳和下一个 netCDF 文件的第一个时间戳之间差异的功能?
- python-3.x - 尝试通过 Pyinstaller 创建 exe 文件时,找不到隐藏的导入“pysqlite2”!
- javascript - 是否可以抑制 Durandal 导航?