0

我正在研究一种以递归方式删除 ArrayList 中元素的重复项的方法。但是我遇到了一些问题,我的方法有效并删除了一些元素,但不是所有的重复项。

这是我的输入:

100, 200, 200, 300, 400, 300, 100, 500, 500, 400, 100, 400, 100, 100

这是输出:

100, 200, 300, 400, 100, 500, 100

还有我的方法:

public static void removeDuplicates(ArrayList<Integer> list, int counter){
    if(list == null){
        throw new NullPointerException();
    }

    if(counter < list.size()){
        if(list.contains(list.get(counter))){
            list.remove(list.lastIndexOf(list.get(counter)));
        }
        removeDuplicates(list, ++counter);
    }
}

我知道我只是删除所述值的最后一个元素,然后迭代到下一个元素。我想知道如何更改它以删除所有重复的元素。此外,我的输出中让我感到困惑的一部分是,“400”有三个值,但输出中只显示了一个。

谢谢您的帮助。

4

5 回答 5

2

除了@NPE 是正确的(我认为这是家庭作业)之外,您应该考虑使用相同的头部调用您的函数,只要找到重复的元素。如果没有找到重复项(不再),则仅使用下一个元素(即,增加counter)。

于 2013-03-16T17:32:31.353 回答
1

list.remove()将减少list.size(),这意味着每次您删除一个项目并推进counter时,您最终都会跳过一个。

于 2013-03-16T17:28:51.080 回答
1

试试这个:

    public static void removeDuplicates(ArrayList<Integer> list, int counter){


        if(list == null){
            throw new NullPointerException();
        }

        if(counter < list.size()){
            if(list.contains(list.get(counter))){
                if(list.lastIndexOf(list.get(counter))!=counter)
                {
                    list.remove(list.lastIndexOf(list.get(counter)));
                    counter--;
                }
            }
            removeDuplicates(list, ++counter);
        }

    }
于 2013-03-16T17:35:10.640 回答
0

我的第一个问题是你为什么要使用递归?简单地从旧列表构建一个新列表要简单得多。

如果您处理调用序列,从字符串中删除项目,您会发现输出符合预期。

通过 1 删除最后的 100

100, 200, 200, 300, 400, 300, 100, 500, 500, 400, 100, 400, 100

通过 2 删除最后的 200

100、200、300、400、300、100、500、500、400、100、400、100

通过 3 删除最后的 300

100、200、300、400、100、500、500、400、100、400、100

通过 4 删除最后的 400

100、200、300、400、100、500、500、400、100、100

Pass 5 删除最后 100 个

100、200、300、400、100、500、500、400、100

通过 6 删除最后的 500

100、200、300、400、100、500、400、100

Pass 7 什么都不删除 Pass 8 什么都不删除

于 2013-03-16T17:33:09.373 回答
0

尝试

    if (counter < list.size()) {
        int i = list.lastIndexOf(list.get(counter));
        if (i > counter) {
            list.remove(i);
        } else {
            counter++;
        }
        removeDuplicates(list, counter);
    }
于 2013-03-16T17:45:42.503 回答