列表中的Java重复元素

时间:2014-05-22 06:35:36

标签: java

我有以下程序来查找列表中的重复元素。它仅适用于列表中的少数元素。我在过去的30分钟内打破了我的头脑,但我无法弄清楚我的错误:(需要一些专家建议!

public class CheckDuplicateInList {
public static void main(String[] args) {
    List<Integer> lst = Arrays.asList(1,2,1,4,1,2,3,4);
    checkDuplicateInList(lst);      
}

public static boolean checkDuplicateInList(List<Integer> intList) { 
    Map<Integer,Integer> ctMap = new HashMap<Integer,Integer>();
    for(int i=0;i<intList.size();i++) {
        for(int j=i+1;j<intList.size();j++) {
            if(intList.get(i) == intList.get(j)) {
                if(ctMap.containsKey(intList.get(i))) {
                        ctMap.put(intList.get(i),ctMap.get(intList.get(i))+1);  
                        break;
                }
                    else {
                        ctMap.put(intList.get(i),1);                            
                    }
                }
            }
        }
        System.out.println("Duplicate elements in the List: ");
        for(Map.Entry<Integer, Integer> ctMapVals:ctMap.entrySet()) {
            System.out.println(ctMapVals.getKey()+ " occurs " +ctMapVals.getValue()+ " times");
        }



    return false;
    }
}

这是程序输出 -

Duplicate elements in the List: 
1 occurs 3 times
2 occurs 1 times
4 occurs 1 times

为什么它没有为2和4给出正确的结果?请指教

3 个答案:

答案 0 :(得分:1)

您提供了许多完全不需要的额外代码。删除内部for循环和if语句,该语句会比较列表中的ithjth元素。

containsKey()方法足以检查Map中是否已存在该号码。 if(intList.get(i) == intList.get(j)) {只是一种矫枉过正,这使得你的逻辑可以用来折腾。

for (int i = 0; i < intList.size(); i++) {
    if (ctMap.containsKey(intList.get(i))) {
        ctMap.put(intList.get(i), ctMap.get(intList.get(i)) + 1);
    } else {
        ctMap.put(intList.get(i), 1);
    }
}

使用上述代码段时的输出:

Duplicate elements in the List: 
1 occurs 3 times
2 occurs 2 times
3 occurs 1 times
4 occurs 2 times

答案 1 :(得分:0)

试试这个

    public static boolean checkDuplicateInList(List<Integer> intList) {
        Map<Integer, Integer> ctMap = new HashMap<Integer, Integer>();
        for (int e : intList) {
            if (ctMap.containsKey(e)) {
                ctMap.put(e, ctMap.get(e) + 1);
            } else {
                ctMap.put(e, 1);
            }
        }
...

答案 2 :(得分:0)

您的for循环逻辑错误。它为每个匹配放置了值1(即使没有匹配也会忘记它,至少有一个元素)..所以for循环的正确代码是:

 for(int i=0;i<intList.size();i++) {
        if(!ctMap.containsKey(intList.get(i))) {
             ctMap.put(intList.get(i),1);  
        }
        for(int j=i+1;j<intList.size();j++) {
            int  iKey = intList.get(i);
            int jKey = intList.get(j);
            if(iKey == jKey) {
                        ctMap.put(intList.get(i),ctMap.get(intList.get(i))+1);  
                        //break;


                }
            }
        }