当我声明let属性与方法参数相同时, 运行速度为72毫秒(测试10多次试验)。
如果我声明为差异名称,则运行速度为48xx毫秒。 (测试10多个试验)
有人可以告诉我发生了什么事吗? 谢谢。
密码问题: https://leetcode.com/problems/find-all-anagrams-in-a-string/submissions/
/*
Time Submitted Status Runtime Memory Language
a few seconds ago Accepted 72 ms 22.2 MB swift
*/
class Solution {
func findAnagrams(_ s: String, _ p: String) -> [Int] {
var result = [Int]()
var ref = Array<Int>(repeating: 0, count: 26)
var map = ref
let p = p.unicodeScalars
.map{ $0.value - Unicode.Scalar("a").value }
.map{ Int($0) }
let s = s.unicodeScalars
.map{ $0.value - Unicode.Scalar("a").value }
.map{ Int($0) }
p.forEach{ ref[$0] += 1 }
for i in 0..<s.count {
map[s[i]] += 1
if i - p.count >= 0 {
map[s[i-p.count]] -= 1
}
if map == ref {
result.append(i - p.count + 1)
}
}
return result
}
}
/*
Time Submitted Status Runtime Memory Language
a few seconds ago Accepted 4868 ms 22 MB swift
*/
class Solution {
func findAnagrams(_ s: String, _ p: String) -> [Int] {
var result = [Int]()
var ref = Array<Int>(repeating: 0, count: 26)
var map = ref
let pTest = p.unicodeScalars
.map{ $0.value - Unicode.Scalar("a").value }
.map{ Int($0) }
let sTest = s.unicodeScalars
.map{ $0.value - Unicode.Scalar("a").value }
.map{ Int($0) }
pTest.forEach{ ref[$0] += 1 }
for i in 0..<s.count {
map[sTest[i]] += 1
if i - p.count >= 0 {
map[sTest[i-p.count]] -= 1
}
if map == ref {
result.append(i - p.count + 1)
}
}
return result
}
}