简体   繁体   English

从Java中的阵列中删除重复项

[英]Removing duplicates from an Array in Java

I have an array of type long and I'm just trying to make a code that will find and remove duplicates. 我有一个long类型的数组,我只是想制作一个可以查找和删除重复项的代码。 It somewhat works, but it has some bugs. 它有些奏效,但有一些错误。 I'm not sure what I'm doing wrong. 我不确定自己在做什么错。 I'd really appreciate the help. 我非常感谢您的帮助。

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,33,0,0

and the output is : 77, 44, 22, 11, 66, 33, 55, 55, 99, 99 输出为:77、44、22、11、66、33、55、55、99、99

so it erased the 33 duplicate and both 0's and completely skipped 55 and 99. 因此它删除了33个重复项和两个0,并完全跳过了55和99。

Here is my code so far: 到目前为止,这是我的代码:

nElems is the size of the array nElems是数组的大小

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! 将很快完成您需要的一切!

In noDups, j is a position in the index. 在noDups中,j是索引中的位置。 You're calling delete(j), but your delete method is expecting a value rather than a position. 您正在调用delete(j),但是您的delete方法期望值而不是位置。 You need to change one or the other (and using the position rather than the value is probably your better option). 您需要更改一个或另一个(使用位置而不是值可能是更好的选择)。

Your issue lies in your delete method. 您的问题出在删除方法上。 Try passing it an index of an array (since j is your duplicate in the array, try j). 尝试将其传递给数组的索引(因为j是您在数组中的重复项,请尝试j)。 Within your delete, remove that index by overriding it with indexes past it in the array. 在删除中,通过用数组中过去的索引覆盖该索引来删除该索引。 To remove it simply: 要简单地删除它:

for(int i = j; i<a.length - 1; i++){
    a[i] = a[i+1];
}

and then set a.length to null 然后将a.length设置为null

a[a.length] = null;

This is only if having nulls within the array is ok, if not then you need to create a new array that stores everything in array a up to j, and then from j on stores j+1. 只有在数组中包含null的情况下,这是必须的,否则,您需要创建一个新数组,将数组a中的所有内容存储到j,然后从j存储j + 1。 It would then need to return it or you would need to set a to the new array. 然后它将需要返回它,或者您需要将a设置为新数组。 The reason it is a.length - 1 is because if you do just a.length, it will loop through to the end of your array and try to set your last value to an unknown value out of index. 它是a.length-1的原因是,如果仅执行a.length,它将循环到数组的末尾并尝试将最后一个值设置为索引之外的未知值。 This isn't the best solution, but is a solution assuming that you are supposed to work with looping through arrays and not actually using Java classes. 这不是最佳解决方案,但是是一个假定您应该使用遍历数组而不实际使用Java类的解决方案。

I think the answers are over complicating your homework. 我认为答案已经使您的作业复杂化了。 The simplest solution is the following: 最简单的解决方案如下:

//noDoup partial code
if (list[i] == list[j])
{
    duplicates++;
    delete(j);
    nElems--;
    j--;//you missed this
}
//delete() is simply this
public boolean delete(long value)
{
    System.arraycopy(list, j+1, list, j, nElems-j-1);
}

The resulting array is Arrays.copyOf(list, nElems); 结果数组为Arrays.copyOf(list, nElems);

public class Arrayremoveduplicates {
    /**
     * @param args
     */
    public static void main(String[] args) {
        String[] Origarray = { "10", "20", "30" };
        System.out.println("Original array with duplicates :");
        for (int a = 0; a < Origarray.length; a++) {
            System.out.print(Origarray[a] + " ");
        }
        System.out.println();
        System.out.println("Result array without duplicates :");
        for (int i = 0; i < Origarray.length; i++) {
            int duplicate = 0;
            for (int j = i + 1; j < Origarray.length; j++) {
                if (Origarray[i] == Origarray[j]) {
                    duplicate = duplicate + 1;
                }
            }
            if (duplicate == 0) {
                System.out.print(Origarray[i] + " ");
            }
        }
    }
}

package com.sparity; 包比较 import java.util.*; 导入java.util。*;

class RemoveDuplicates { 类RemoveDuplicates {

public static void main(String[] args) {
    Integer[] array = new Integer[10];

    array[0] = 1;
    array[1] = 2;
    array[2] = 3;
    array[3] = 3;
    array[4] = 3;
    array[5] = 3;
    array[6] = 7;
    array[7] = 7;
    array[8] = 9;
    array[9] = 9;
    removeDuplicatesFromArray(array);

}


private static void removeDuplicatesFromArray(Integer[] array){
    StringBuffer stringBuffer = new StringBuffer();
     String arrayString =  Arrays.toString(array);
     for(int index =0 ; index <= arrayString.length(); index++){
      try{
          int number = Integer.parseInt(arrayString.charAt(index)+"");
          if(!stringBuffer.toString().contains(number+"")){
          if(stringBuffer.length()!=0)
              stringBuffer.append(",");
             stringBuffer.append(number);
          }

      }catch(Exception e){

      }
     }
     String[] stringArray = stringBuffer.toString().split(",");
     array = new Integer[stringArray.length];
     for(int index = 0 ; index < stringArray.length ; index++){
       array[index] = Integer.parseInt(stringArray[index]); 
     }
     System.out.println(Arrays.toString(array));
  }

} }

I would use Map to remove the duplicates as follows. 我将使用Map删除重复项,如下所示。

public class RemoveDuplicates {
 public static void main(String args[]) {
    int[] array = { 1, 34, 23, 54, 2, 1, 34, 2 };
    int j = 0;
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (int i = 0; i < array.length; i++) {
        //true if the current element is already present
        if (!map.containsKey(array[i])) {
            map.put(array[i], array[i]);
        }
    }
    //just print all the elements without converting into array
    System.out.println(map.keySet().toString());
    int[] uniqueElements= new int[map.keySet().size()];
    //Convert keys into array
    for (Integer s : map.keySet()) {
        uniqueElements[j++] = s;
    }
 }
}

I had to do this for a class assignment and disliked the answers here. 我必须在上课时这样做,不喜欢这里的答案。 They were either overly complex, or too simple and inefficient. 它们要么过于复杂,要么过于简单和低效。 I like having a happy medium, so I threw this together: 我喜欢有一个快乐的媒介,所以我把它放在一起:

public static int[] exercise6(int[] array) {
    int del = 0;
    for( int i = 0; i < array.length - (1 + del); ++i ) {
        for( int j = array.length - (1 + del); j > i; --j ) {
            if( array[i] == array[j]) {
                for( int k = j; k < array.length - (1 + del); ++k ) {
                    array[k] = array[k + 1];
                }
                array[array.length - 1] = 0;
                del++;
            }
        }
    }
    return Arrays.copyOfRange(array, 0, array.length - del);

If you don't need to truncate the array itself you can always just return array instead. 如果您不需要截断数组本身,则始终可以返回数组。

private Map<Integer, Integer> getUniqueArray(int[] duplicateArray) {
    Map<Integer, Integer> uniqueMap = new HashMap<>();
    int count = 0;
    for (int element : duplicateArray) {
        count = 0;
        if (uniqueMap.get(element) != null) {
            ++count;
        }
        if (count == 0) {
            uniqueMap.put(element, count);
        }
    }
    return uniqueMap;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM