2014-09-05 56 views
6

主要問題:將項目插入已使用Julia排序的列表中的最快方式是什麼?將項目插入Julia的排序列表(帶和不帶重複項)

目前,我這樣做:

v = [1, 2, 3, 5] #example list 
x = 4 #value to insert 
index = searchsortedfirst(v, x) #find index at which to insert x 
insert!(v, index, x) #insert x at index 

獎金問題:如果我想同時保證沒有重複怎麼辦?

回答

5

您可以使用searchsorted獲得其中值出現,而不只是第一個指數的範圍,然後使用splice!一套新的價值觀,以取代在該範圍內的值:

insert_and_dedup!(v::Vector, x) = (splice!(v, searchsorted(v,x), [x]); v) 

這一個很好的小單線,可以做你想做的事。

julia> v = [1, 2, 3, 3, 5]; 

julia> insert_and_dedup!(v, 4) 
6-element Array{Int64,1}: 
1 
2 
3 
3 
4 
5 

julia> insert_and_dedup!(v, 3) 
5-element Array{Int64,1}: 
1 
2 
3 
4 
5 

這讓我覺得splice!應該處理,其中更換單個值,而不是一個數組的情況下,所以我可能會增加該功能。

+0

謝謝,這非常整齊。 – 2014-09-06 05:58:44

+0

我改變了拼接!以允許替換參數是任何可枚舉的,其中包括標量值:https://github.com/JuliaLang/julia/commit/e048f2bf1b8da56b07738c0a4d142cd29e140e98。你現在可以定義'insert_and_dedup!(v :: Vector,x)=(splice!(v,searchsorted(v,x),x); v)'。 – StefanKarpinski 2014-09-17 14:49:42

+1

謝謝,也感謝你在朱莉婭的所有工作。我很喜歡這門語言。 – 2014-09-18 06:43:40