保持原样,仅循环一次,保留顺序:
nameArray := ["Chris","Joe","Marcy","Chris","Elina","Timothy","Joe"]
trimmedArray := trimArray(nameArray)
trimArray(arr) { ; Hash O(n)
hash := {}, newArr := []
for e, v in arr
if (!hash.Haskey(v))
hash[(v)] := 1, newArr.push(v)
return newArr
}
使用haskey方法的替代方法是检查哈希对象中的值。这可能会被证明更有效,更快捷,但是我将把测试交给您。
trimArray(arr) { ; Hash O(n)
hash := {}, newArr := []
for e, v in arr
if (!hash[v])
hash[(v)] := 1, newArr.push(v)
return newArr
}
编辑:起初我不打算测试,但我既好奇又厌倦了等待OP。结果并不令我感到惊讶:
我们在这里看到的是10,000个测试的平均执行时间,该数字越小,任务的计算速度就越快。明显的赢家是我的脚本版本没有Haskey方法,但是只有很少的利润!所有其他方法都注定要失败,因为它们不是线性解。
测试代码在这里:
setbatchlines -1
tests := {test1:[], test2:[], test3:[], test4:[]}
Loop % 10000 {
nameArray := ["Chris","Joe","Marcy","Chris","Elina","Timothy","Joe"]
QPC(1)
jimU(nameArray)
test1 := QPC(0), QPC(1)
AbdullaNilam(nameArray)
test2 := QPC(0), QPC(1)
ahkcoderVer1(nameArray)
test3 := QPC(0), QPC(1)
ahkcoderVer2(nameArray)
test4 := QPC(0)
tests["test1"].push(test1), tests["test2"].push(test2)
, tests["test3"].push(test3), tests["test4"].push(test4)
}
scripts := ["Jim U ", "Abdulla Nilam "
, "ahkcoder HasKey", "ahkcoder Bool " ]
for e, testNums in tests ; Averages Results
r .= "Test Script " scripts[A_index] "`t:`t" sum(testNums) / 10000 "`n"
msgbox % r
AbdullaNilam(names) {
for i, namearray in names
for j, inner_namearray in names
if (A_Index > i && namearray = inner_namearray)
names.Remove(A_Index)
return names
}
JimU(nameArray) {
hash := {}
for i, name in nameArray
hash[name] := null
trimmedArray := []
for name, dummy in hash
trimmedArray.Insert(name)
return trimmedArray
}
ahkcoderVer1(arr) { ; Hash O(n) - Linear
hash := {}, newArr := []
for e, v in arr
if (!hash.Haskey(v))
hash[(v)] := 1, newArr.push(v)
return newArr
}
ahkcoderVer2(arr) { ; Hash O(n) - Linear
hash := {}, newArr := []
for e, v in arr
if (!hash[v])
hash[(v)] := 1, newArr.push(v)
return newArr
}
sum(arr) {
r := 0
for e, v in arr
r += v
return r
}
QPC(R := 0) ; https://autohotkey.com/boards/viewtopic.php?t=6413
{
static P := 0, F := 0, Q := DllCall("QueryPerformanceFrequency", "Int64P", F)
return ! DllCall("QueryPerformanceCounter", "Int64P", Q) + (R ? (P := Q) / F : (Q - P) / F)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句