2017-08-08 77 views
0

我想加快我的代碼。快速狀態信息:JAVA - 加速代碼

  • 有一個以上的列表(String)像_list1_list2_list3

  • 我試圖在這些列表中找到一個單詞(String)。

  • 如果我找到一個單詞,我將使用列表中的單詞索引。

這裏是我的代碼:

private static int foundIndex (String s) 
{ 
    if (_list1.contains(s)) { 
     return _list1.indexOf(s); 
    } else if (_list2.contains(s)) { 
     return _list2.indexOf(s); 
    } else if (_list3.contains(s)) { 
     return _list3.indexOf(s); 
    } else if (_list4.contains(s)) { 
     return _list4.indexOf(s); 
    } 
... 
... 
... 
... 
    } else if (_list100.contains(s)) { 
     return _list100.indexOf(s); 
    } 
    return -1; 
} 

我怎樣才能加快我的代碼?

+0

您可以將's'映射到'Map '中的索引。 –

+1

什麼是Java版本? – Euclides

+1

列表不知道時返回索引...是不是太可用 –

回答

1

添加所有的列表(String)在List<String>和遍歷它:

private static int foundIndex (String s) { 
    for (String currentList : lists){ 
     int indexOf = currentList.indexOf(s); 
     if (indexOf != -1) { 
      return indexOf; 
     } 
    } 
    return -1; 
} 
+0

列表未知時的返回索引...不是太多可用(像在初級解決方案中) –

+1

@Jacek Cz可能。我不知道需要。通過一些修改,它可以返回包含索引和列表的自定義類「ListAndIndex」。 – davidxxx

2

幾個簡單的優化想到:

1.replace的if (contains) then indexOf圖案if (i = indexOf(s) >= 0) return i

2.添加查找數據結構,如Map<String,Integer>,或者使用它來代替列表或者除了它們之外通過更新它來添加或更改列表

0

我將我的代碼算法改爲您的建議。 我之前的使用清單很多,現在我改變了它。我使用2D String數組。但代碼性能下降了157%。

新代碼:

private static String[][] _lists = new String[200][100]; 

private static int foundIndex (String s) { 
for (int i = 0; i < 200; i++) { 
     for (int j = 0; j < 100; j++) { 
      if (_lists[i][j].equals(s) == true) { 
       return j; 
      } 
     } 
    } 
    return -1; 
} 

這就是問題的開始。

如果我正在查找的代碼是「_list [180] [?]」,那麼很難找到它。

如何加快我的代碼?

謝謝。