2

我遇到了这个问题:我要编写一个方法 contains3,它接受一个字符串列表作为参数,如果任何单个字符串在列表中至少出现 3 次,则返回 true,否则返回 false。我需要使用地图。

当一个词出现三个实例时,仍然不返回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;
}
4

5 回答 5

3

问题在这里:

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

您应该使用键获取值,换句话说,word您正在计数。

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

请注意,我return false;从该if语句中删除了 ,因为它会在第一次迭代中破坏该方法。


作为建议,您可以使用 aHashMap而不是TreeMap提高方法的性能,因为inputgettime inHashMap是 O(1)(恒定时间),而TreeMap's 是 O(log n)。

于 2013-10-12T05:15:27.943 回答
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;}
于 2013-10-12T05:23:47.627 回答
1

添加每个单词时,您正在运行此代码:

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

添加第一个单词时测试将失败,您将立即返回false。将该块移到方法的末尾,在最后一行中,您当前return false只需在计算完所有单词后进行检查。

于 2013-10-12T05:20:18.427 回答
1

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

在 for 循环之外

于 2013-10-12T05:23:50.550 回答
0

在初始 if 块中检查 count 是否 >= 3 效率更高

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

并删除以下 if else 块

    if (wordCount.containsValue(3)) {
        return true;
    } else {
        return false;
    }
于 2013-10-12T05:29:27.803 回答