< p > @Colin 提供了一个简洁、方便的答案。然而,如果速度很重要(op 要求最有效的方法),那么这应该接近最优解。 < /p >
function findlongest(A)
idx = 0
len = 0
@inbounds for i in 1:length(A)
l = length(A[i])
l > len && (idx = i; len=l)
end
return A[idx]
end
请注意,这种实现方法在Python中可能是个非常糟糕的想法 :)
快速基准测试:
julia> using BenchmarkTools
julia> A = [[1,2], [1,2,3,4,5,6], [1,2,3]]
3-element Array{Array{Int64,1},1}:
[1, 2]
[1, 2, 3, 4, 5, 6]
[1, 2, 3]
julia> @btime findlongest(A);
26.880 ns (0 allocations: 0 bytes)
julia> @btime A[indmax(length.(A))];
9.813 μs (25 allocations: 1.14 KiB)
这个例子的速度提升了约365倍。
编辑:更好的基准测试(评论中建议)
julia> @btime findlongest($A);
9.813 ns (0 allocations: 0 bytes)
julia> @btime $A[indmax(length.($A))];
41.813 ns (1 allocation: 112 bytes)
$
符号避免了设置分配和时间。加速约为
4。
快速解释
- 在 Julia 中,for 循环很快,所以为什么不使用它们
- 避免分配 (
length.(A)
分配了一个新的整数数组)
a && b
是“如果 a 那么 b”的快捷方式
@inbounds
避免对 A[i]
进行边界检查
4个元素的数组{Int64,1}:1 2 5 8
- Jarbou