2013-07-25 1 views
0

나는 약간의 자바 코드를 작성 중이다 나는 메소드를 작성했고 테스트 입력을 위해 실행하는데 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()); 
} 
+0

왜 5 초 미만을 유지 하시겠습니까? – Jeffrey

+1

프로필러를 사용해 보셨습니까? http://visualvm.java.net/ – radai

+0

그게 뭐야 requiremebt (<5sec) – Sravan2023

답변

2

첫 번째 최적화로 그렇게 indexOf()의 첫 번째 호출이 실제로 필요 유일 변경되지 않습니다 외부 루프 point 변수 중 indexOf()

에 중복 호출을 제거 할 수 있습니다.

// index is the indexes of paraWordsIndexes 
startIndex =paraWordsIndexes.indexOf(point); 

대신 indexOf()의 결과를 저장하는 것, 그리고, 상기 변수 indexOf(point) 모든 발행 수를 변경 루프

int pointLFIndex = paraWordsIndexes.indexOf(point); // new variable. should not change 
startIndex = pointLFIndex; 

내부 변하지 않을 것 새로운 변수를 도입.

// you don't need this. change to for (int index = pointLFIndex; ...); 
for (int index = paraWordsIndexes.indexOf(point); index >= 0; index--) 

// use for (int start = ...; start <= pointLFIndex ...; index++) { 
for (int start = ...; start <= paraWordsIndexes.indexOf(point) ...; index++) { 

indexOf()은 배열 목록을 선형으로 검색합니다. 특히 루프 반복마다 두 번째 발생이 실행되므로 큰 목록의 킬러가됩니다.

위의 내용이 도움이되지 않으면 간단한 테스트를 추가하기 위해 질문을 편집하지 않는 이유가 무엇인지 이해할 수 없습니다 많은 사람들이 당신에게 (나 자신을 포함해서) 물어 봤기 때문에 이 같은

간단한 시나리오 :

입력 텍스트 : "Some words are larger while some other words are smaller"

paraWordsList는 : 예를 들어, 위의 텍스트 문자열 분할을 포함 { "일부", "단어", ...}

paraWordsIndexes : 의 색인을 포함합니다. 예 : {0, 3}

lowFreqIndexes : 예 :{0, 1}

예상 출력 :이가 {값} 그러나 {OTHER_VALUE}하지를 반환해야

1

귀하의 코드가 복잡한 것으로 보인다 (대한 -에 - 경우)는 실행 과정에서 많은 시간이 소요되는 코드입니다 확인을위한 프로파일 러를 사용하고 최적화하는 가장 좋은 방법은이 경우이다. 당신이 당신의 IDE를 지정하지 않기 때문에

, y는 몇 가지 흥미로운 도구를 제안하려고합니다 : 당신이하지 않은 경우

https://profiler.netbeans.org/ http://www.eclipse.org/tptp/

안부

0

글쎄, 그것은 도움이 될 것이다 중첩 된 루프가있는 경우 각 루프 내의 if 문의 수를 최소화 할 수 있다면 도움이 될 것입니다 (특히 중첩 루프가있는 경우).

당신이하려는 것을 설명 할 수 있습니까? 코드가 완전히 분명한 것은 아니며 아마도 접근 방식과 완전히 다른 방식 일 수 있습니다.

+0

나는 텍스트를 정말 복잡하게 설명한다. 내가 생각할 수있는 것은 algo cant가 변경 될 수있는 자바 최적화입니다. – Sravan2023

+0

시도해보십시오. 당신이 그것을 텍스트로 설명 할 수 없다면, 당신이 그것을 완전히 이해할 수없는 현재의 구조라고 생각할 수 있을지 확신 할 수 없습니다. 특별히 구체적인 것은 필요하지 않습니다. 종종 최적화는 if 문 제거와 같은 작은 작업이 아니라 수행중인 프로세스 변경으로 발생합니다. 그 중첩 된 루프를 없애기 위해 노력하고 싶지만, 내가 무엇을하는지 모르는 경우에는 그렇게 할 수 없습니다. –

+0

목록의 큰 단어를 paraWordsList로 부를 수 있습니다. 그런 다음 고유 한 단어 목록을 단어 목록으로 말할 수 있습니다. paraWordsList에는 wordsList에있는 단어와 wordsList에없는 단어가 들어 있습니다. 내 목표는 wordsList에있는 모든 단어를 포함하는 paraWordsList의 시작 및 끝 색인을 찾고 짧은 것이어야합니다. [두 개의 색인 사이에 단어의 수가 다른 어떤 경우보다 적어야 함을 의미합니다]. – Sravan2023