递归 - 删除重复项 [英] Recursion - Removing Duplicates

查看:113
本文介绍了递归 - 删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on a method which removes duplicates of an element in an ArrayList, recursively. But I'm running into a bit of a problem, my method works and removes some elements, but not all of the duplicates.

这是我的输入:

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',但只有一个显示在输出

I understand that I'm only removing the last element of said value, and then iterating to the next one. I was wondering how I should change this to remove all elements that are duplicates. Also, one part of my output that confuses me is, there are three values of '400', yet only one shows up in the output.

感谢您的帮助。

推荐答案

试试这个:

    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);
        }

    }

这篇关于递归 - 删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆