[英]Is it worth using a HashMap in this instance for speed?
我有一個調用距離函數的函數。 距離函數計算兩個輸入字符串之間的 Levenshtein 距離算法。 我試圖找到輸入的單詞(拼寫錯誤)和要返回的英語單詞(使用它作為拼寫檢查器)之間的最短距離,但我不確定我的 HashMap 是否在速度上獲得了任何進展。 wordContainer 是一個包含 n 個單詞的數組,這是否會使我的查找時間停留在 O(n) 中?
private static String findClosestMatch(String word) {
Map<Integer, String> wordAndDistanceMap = new HashMap<>();
wordContainer.forEach(s -> wordAndDistanceMap.put(distance(s, word), s));
return wordAndDistanceMap.get(Collections.min(wordAndDistanceMap.keySet()));
}
雖然這具有合理的時間復雜度,但它有很多開銷來做你永遠不需要的工作/創建對象。 我建議有一個簡單的循環。
private static List<String> findClosestMatch(String word) {
int min = Integer.MAX_VALUE;
List<String> minWords = new ArrayList<>();
for (String s : wordContainer) {
int dist = distance(s, word);
if (dist < min) {
min = dist;
minWords.clear();
}
if (dist == min)
minWords.add(s);
}
return minWords;
}
您必須計算從word
到 N 個其他單詞的 Levenshtein 距離。 計算距離N次是O(N)。
改進O(N)
的唯一方法是設計一種方法來避免計算距離O(N)
次。
HashMap
對此HashMap
。 您需要做的(我不知道這是否可行)是設計一種方法來避免檢查與word
相距“很遠”的word
距離。
好吧,如果您需要比這更快的方法,那么您必須使用索引機制。
我可以建議你是Apache Lucene 。 它是一個開源且廣泛使用的數據索引框架。 此外,還有一些開發版本如Apache SOLR和Elastic Search構建在 Lucene 核心上。 您可以在提供的鏈接上閱讀更多內容。
在為靜態列表建立索引,或為通過它們計算的值建立索引后,您可以在很短的時間內檢索它們,這是您當前所需的。
我希望這將有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.