私はいくつかの Java コードを書いています。私はメソッドを書きました。テスト入力の実行には 5 秒以上かかります。5 秒以内に抑えたいと思っています。メソッドを最適化する方法を教えてください。
private static String getShortestSub(ArrayList<String> paraWordsList,
ArrayList<Integer> paraWordsIndexes,
ArrayList<Integer> lowFreqIndexes) {
long d = System.currentTimeMillis();
// Finding the substring
int startTxtIndex = 0, endTxtIndex = 0;
int tempLength = paraWordsList.size();
for (int i = 0; i < lowFreqIndexes.size(); i++)
{
int point = lowFreqIndexes.get(i), startIndex = 0;
HashSet<String> frame = new HashSet<String>();
// index is the indexes of paraWordsIndexes
startIndex =paraWordsIndexes.indexOf(point);
for (int index = paraWordsIndexes.indexOf(point); index >= 0; index--)
{
if (frame.add(paraWordsList.get(paraWordsIndexes.get(index))))
{
startIndex = index;
if (frame.size() == K
|| (paraWordsIndexes.get(startIndex) - point) >= tempLength)
index = -1;
}
}
frame.clear();
for (int start = startIndex, index = startIndex; start <= paraWordsIndexes
.indexOf(point) && index < paraWordsIndexes.size(); index++)
{
int tempStart = paraWordsIndexes.get(start), tempEnd = paraWordsIndexes.get(start);
int currIndex = paraWordsIndexes.get(index);
String word = paraWordsList.get(currIndex);
if ((tempStart - point) >= tempLength) break;
if ((tempStart - currIndex) >= tempLength) break;
frame.add(word);
if (frame.size() == K)
{
tempEnd = currIndex;
int newLength;
if ((newLength = tempEnd - tempStart) > 0)
if (tempLength > newLength)
{
tempLength = newLength;
startTxtIndex = tempStart;
endTxtIndex = tempEnd;
if (K == (tempLength+1)) {
i = lowFreqIndexes.size();
break;
}
}
frame.clear();
tempStart = paraWordsList.size();
start++;
index = start - 1;
}
}
frame.clear();
System.out.println(System.currentTimeMillis() - d);
}
String[] result = paraText.split(" ");
ArrayList<String> actualParaWordsList = new ArrayList<String>(
Arrays.asList(result));
return textCleanup(actualParaWordsList.subList(startTxtIndex,
endTxtIndex + 1).toString());
}