2016-05-27 39 views
0

我有一個排序的字符串數組。在這個數組中有沒有一種快速查找和元素的方法?在排序數組中快速找到元素

我想優化以下功能。這需要很長時間。傳遞的數組不長(只有約15-20元),但它被稱爲很多(約1000倍)。目前我只是做了.filter { }但我認爲這可能是一個瓶頸,因爲它經過了全陣列1000次而不是在找到第一個這樣的日曆時發生。

是否有被優化一個內置的搜索(即,使用非常小的陣列然後中型或較大的一種不同的方法)類似內置排序功能?

基本上,我在尋找對方的內置分頁/排序功能。這樣做會很有意義,因爲您經常對數組進行排序,然後在其中查找特定的元素。

func startsWithACalendarName(text: String, calendars: [EKCalendar], stripKeywords: Bool = false) -> (newReminderText: String, foundCalendar: EKCalendar?) { 
    // make array of words from text 
    let words = text.characters.split{$0 == " "}.map(String.init) 
    // BOTTLENECK? Check if I have a calendar that is equal to first word of text 
    let found = calendars.filter { $0.title.lowercaseString == words.head?.lowercaseString } 
    return (stripKeywords ? (words.tail?.joinWithSeparator(" "))! : text, found.first) 
} 
+0

問題標題是如何與這個問題的身體嗎? –

+0

對不起,更正了。 – Daniel

+1

如果已經排序,您可以使用二進制搜索。 –

回答

0

我認爲你可以解決的,而不是「過濾器」這個使用「的indexOf」:

func startsWithACalendarName(text: String, calendars: [EKCalendar], stripKeywords: Bool = false) -> (newReminderText: String, foundCalendar: EKCalendar?) { 
    let words = text.characters.split{$0 == " "}.map(String.init) 
    var found: EKCalendar? 
    if let index = calendars.indexOf ({ $0.title.lowercaseString == words.head?.lowercaseString }) { 
     found = calendars[index] 
    } 
    return (stripKeywords ? (words.tail?.joinWithSeparator(" "))! : text, found) 
} 
+0

但是,這是否考慮到數組已經排序?因爲搜索排序數組要比在非排序數組中搜索索引快得多。 – Daniel

+0

它應該比使用'filter'更好。在這一點上,我會做一個小測試來衡量兩者的運行時間,看看它是否足夠好。 – orxelm