2013-10-12 24 views
2

我遇到了這個問題:我要編寫一個方法contains3,接受一個字符串列表作爲參數,並返回true,如果任何單個字符串在列表中至少出現3次,並且否則爲假。我需要使用地圖。檢測列表中的多個值

當一個單詞有三個實例時,它仍然不返回true;我無法找到出錯的地方。

以下是我有:

private static boolean contains3(List<String> thing) { 
    Map<String, Integer> wordCount = new TreeMap<String, Integer>(); 
    for (String s: thing) { 
     String word = s; 

     if (wordCount.containsKey(word)) { // seen before. 
      int count = wordCount.get(word); 
      wordCount.put(word, count + 1); 
     } else { 
      wordCount.put(word, 1); // never seen before. 
     } 

     if (wordCount.containsValue(3)) { 
      return true; 
     } else { 
      return false; 
     } 

    } 
    return false; 
} 
+1

什麼問題? – Prateek

+0

當一個單詞有三個實例時,它仍然不會返回true;我無法找到出錯的地方。 –

+0

@JackL。你不能從集合中使用本地方法嗎? –

回答

3

的問題是在這裏:

if (wordCount.containsValue(3)) { 
    //... 

你應該使用鍵獲取的價值,換句話說,該word你計數。

if (wordCount.get(word) >= 3) { 
    return true; 
} 

注意,我從這個if語句刪除return false;,因爲它會破壞在第一次迭代的方法。


作爲一個建議,你可以使用HashMap,而不是TreeMap提高因爲putget時間HashMap你的方法的性能是O(1)(恆定時間),而TreeMap的是O(log n)。

+0

此外,'HashMap'在這裏是正確的選擇,而不是'TreeMap'(因爲不需要排序,效率更高)。 – MattR

+0

@MattR建議注意,謝謝。 –

+0

明白了,謝謝。 –

1

你爲你添加的每個字運行此代碼:添加的第一個字時

 if (wordCount.containsValue(3)) { 
      return true; 
     } else { 
      return false; 

,測試將失敗,你會立即返回false。將該塊移到該方法的末尾,在當前有return false的最後一行中,只在您計算所有單詞時進行檢查。

2

請嘗試使用以下代碼。

private static boolean contains3(List<String> thing) { 
    Map<String, Integer> wordCount = new TreeMap<String, Integer>(); 
     thing.add("hi"); 
     thing.add("hi"); 
     thing.add("hi"); 
     thing.add("hia"); 
     thing.add("hi3"); 
     for (String s: thing) { 
      String word = s; 

      if (wordCount.containsKey(word)) { // seen before. 
       int count = wordCount.get(word); 
       wordCount.put(word, count + 1); 
      } else { 
       wordCount.put(word, 1); // never seen before. 
      } 
     } 
      if (wordCount.containsValue(3)) { 
       return true; 
      } else { 
      return false;} 
1

if (wordCount.containsValue(3)) { 
     return true; 
    } else { 
     return false; 
    } 

外部for循環

0

這是更有效的,以檢查是否計數處於初始> = 3,如果塊

if (wordCount.containsKey(word)) { // seen before. 
     int count = wordCount.get(word) + 1; 
     if(count >= 3) { 
       return true; 
     } 
     wordCount.put(word, count); 
    } 

和除去如果其他塊如下

if (wordCount.containsValue(3)) { 
     return true; 
    } else { 
     return false; 
    }