从Java中的阵列中删除重复项 [英] Removing duplicates from an Array in Java
问题描述
我有一个long类型的数组,我只是想编写一个可以查找和删除重复项的代码。它多少有些用,但是有一些错误。我不确定自己在做什么错。我非常感谢您的帮助。
I have an array of type long and I'm just trying to make a code that will find and remove duplicates. It somewhat works, but it has some bugs. I'm not sure what I'm doing wrong. I'd really appreciate the help.
我添加了数字:77、44、22、11、66、33、55、55、99、99、33, 0,0
I added the numbers : 77, 44, 22, 11, 66, 33, 55, 55, 99, 99, 33, 0, 0
,输出为:77、44、22、11、66、33、55、55、99、99
and the output is : 77, 44, 22, 11, 66, 33, 55, 55, 99, 99
因此它删除了33个重复项和两个0,并完全跳过了55和99。
so it erased the 33 duplicate and both 0's and completely skipped 55 and 99.
到目前为止,这是我的代码:
Here is my code so far:
nElems是数组的大小
nElems is the size of the array
public int noDups()
{
int duplicates = 0;
for(int i = 0; i<nElems; i++)
{
for(int j = i+1; j<nElems; j++)
{
if( i == j)
{
break;
}
else if (a[i] == a[j])
{
duplicates++;
delete(j);
nElems--;
}
}// end for j
}// end for i
return duplicates;
}// noDups()
我的删除看起来像这样:
My delete looks like this:
public boolean delete(long value)
{
int j;
for(j=0; j<nElems; j++) // look for it
{
if( value == a[j] )
break;
if(j==nElems) // can’t find it
{
return false;
}
else // found it
{
for(int k=j; k<nElems; k++) // move higher ones down
{
a[k] = a[k+1];
nElems--; // decrement size
return true;
}
}
}// end for i
} // end delete()
推荐答案
public static class Node {
int value;
Node next;
Node prev;
public Node(int value)
{
this.value = value;
}
}
public static class List {
Node[] list = new Node[32];
int size = 0;
public void put(int value) {
int index = value & 31;
for (Node n = list[index]; n != null; n = n.next) {
if (n.value == value) {
return;
}
}
Node newNode = new Node(value);
Node n = list[index];
if (n != null) {
n.prev = newNode;
newNode.next = n;
}
list[index] = newNode;
size++;
}
public void addAll(int[] array) {
for (int x = 0; x < array.length; x++) {
put(array[x]);
}
}
public int[] toArray() {
int[] array = new int[size];
if (size != 0) {
main:
for (int b = 0, i = 0; b < list.length; b++) {
Node n = list[b];
for (; n != null; n = n.next) {
// Place this value in to our array.
array[i++] = n.value;
// We break because our index is larger than our
// available array size.
if (i >= size) {
break main;
}
}
}
}
return array;
}
}
public static void main(String[] args) {
List list = new List();
int[] array = new int[] {77, 44, 22, 11, 66, 33, 55, 55, 99, 99, 33, 0, 0};
list.addAll(array);
System.out.println(Arrays.toString(list.toArray()));
}
为您编写此代码。将很快完成您需要的一切!
Wrote this code out for you. Will do everything you need it todo and very fast!
这篇关于从Java中的阵列中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!