如何使用Java中的辅助阵列用来删除列表重复? [英] How to remove duplicates from a list using an auxiliary array in Java?

查看:147
本文介绍了如何使用Java中的辅助阵列用来删除列表重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过创建存储的副本在哪里指数一个临时数组用来删除列表重复,然后关闭原始数组复制到另一个临时数组,而比较指数的指数我已存储在我的第一个临时数组。

I am trying to remove duplicates from a list by creating a temporary array that stores the indices of where the duplicates are, and then copies off the original array into another temporary array while comparing the indices to the indices I have stored in my first temporary array.

public void removeDuplicates()
{
    double tempa [] = new double [items.length];
    int counter = 0;
    for ( int i = 0; i< numItems ; i++)
    {
        for(int j = i + 1; j < numItems; j++)
        {
            if(items[i] ==items[j])
            {
                tempa[counter] = j;
                counter++;

            }
        }
    }

    double tempb [] = new double [ items.length];
    int counter2 = 0;
    int j =0;
    for(int i = 0; i < numItems; i++)
    {
        if(i != tempa[j])
        {
            tempb[counter2] = items[i];
            counter2++;

        }
        else
        {
            j++;

        }
    }

    items = tempb;
    numItems = counter2;
}

和而逻辑似乎是正确的,我的编译器是给我在

and while the logic seems right, my compiler is giving me an arrayindexoutofbounds error at

tempa[counter] = j;

我不明白怎么会专柜的items.length以上的价值增长到,哪里是逻辑缺陷?

I don't understand how counter could grow to above the value of items.length, where is the logic flaw?

推荐答案

您正在为自己的事情相当困难。让Java的做繁重你。例如LinkedHashSet给你的独特性和保留插入顺序。它也将大于每一个值与所有其他值相比较更有效。

You are making things quite difficult for yourself. Let Java do the heavy lifting for you. For example LinkedHashSet gives you uniqueness and retains insertion order. It will also be more efficient than comparing every value with every other value.

double [] input = {1,2,3,3,4,4};
Set<Double> tmp = new LinkedHashSet<Double>();
for (Double each : input) {
    tmp.add(each);
}
double [] output = new double[tmp.size()];
int i = 0;
for (Double each : tmp) {
    output[i++] = each;
}
System.out.println(Arrays.toString(output));

这篇关于如何使用Java中的辅助阵列用来删除列表重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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