简体   繁体   中英

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. 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

and the output is : 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.

Here is my code so far:

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!

In noDups, j is a position in the index. You're calling delete(j), but your delete method is expecting a value rather than a position. 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). 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[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. It would then need to return it or you would need to set a to the new array. 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. 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.

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

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.*;

class 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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