【问题标题】:Sorted version of inin 的排序版本
【发布时间】:2018-05-08 23:47:30
【问题描述】:

我有一个时间数组event_times,我想检查是否t in event_times。但是,我知道 event_times 已排序。有没有办法利用它来加快搜索速度?

【问题讨论】:

  • 是的,请参阅?searchsorted,以及有用的相关函数?searchsortedfirst?searchsortedlast

标签: arrays sorting search julia


【解决方案1】:

一种惯用的朱利安方式是对以下内容的详细说明:

struct SortedVector{T,V<:AbstractVector} <: AbstractVector{T}
    v::V
    SortedVector{T,V}(v::AbstractVector{T}) where {T, V} = new(v)
    # check sorted in inner constructor??
end
SortedVector(v::AbstractVector{T}) where T = SortedVector{T,typeof(v)}(v)

@inline Base.size(sv::SortedVector) = size(sv.v)
@inline Base.getindex(sv::SortedVector,i) = sv.v[i]
@inline Base.in(e::T,sv::SortedVector{T}) where T = !isempty(searchsorted(sv.v,e))

然后:

julia> v = SortedVector(sort(rand(1:10,10)))
10-element SortedVector{Int64,Array{Int64,1}}:
  1
  4
  5
  5
  6
  6
  6
  7
  7
 10

julia> 3 in v
false

julia> 1 in v
true

如果我没记错的话,David Sanders 有一个使用这个名称的实现。也许查看https://github.com/JuliaIntervals/IntervalOptimisation.jl/blob/889bf43e8a514e696869baaa6af1300ace87b90b/src/SortedVectors.jl 会促进重用。

【讨论】:

    【解决方案2】:

    按照@ColinTBowers 的提示,您可以使用searchsorted 返回一个空范围这一事实,如果t 不在event_times 中。因此!isempty(searchsorted(event_times,t)) 是一种快速获得答案的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-22
      • 1970-01-01
      • 1970-01-01
      • 2019-09-17
      • 2011-12-13
      • 1970-01-01
      • 2019-11-13
      • 1970-01-01
      相关资源
      最近更新 更多