0

Found this solution to make this method:

int[] withoutDuplicates(int[] a){
int n = a.length;
   if (n < 2) {
        return a; 
    }
    for (int i = 0; i < n-1; i++) { 
         for (int j = i+1; j < n; j++) {
               if (a[j] == a[i]) {
                 --n;
                 System.arraycopy(a, j+1, a, j, n-j);
                --j; 
             }//end if
        } //end for
     }//end for

     int[] aa = new int[n]; 
     System.arraycopy(a, 0, aa, 0, n); 
     return aa;

}//end method

I do not understand why it is using an array of length n. Shouldn't it be of size n minus the number of duplicates erased? Is this the most optimal way of implementing the method? or is there any java resource I could use?

2 Answers2

4

I am, by nature, lazy. I would do this:

-- EDIT --

private int[] withoutDuplicates(int[] a){
    Set<Integer> set = new LinkedHashSet<Integer>();
    for (int x : a) {
        set.add(x);
    }
    int[] newArray = new int[set.size()];
    int ii = 0;
    for (Integer x : set) {
        newArray[ii++] = x;
    }
    return newArray;
}
jgitter
  • 3,396
  • 1
  • 19
  • 26
0

Here is an algorithm for removing duplicates and maintaining the relative order. Time: O(n) Space: O(n)

public static void dupCheck(int [] a){
        int j=0;
        HashMap<Integer,Boolean> map = new HashMap<Integer,Boolean>();
        int [] b = new int [a.length];
        for(int i=0;i<a.length;i++){
            if(!map.containsKey(a[i])){
                map.put(a[i],true);
                b[j++]=a[i];
            }
        }
        for(int i=0;i<j;i++)
            System.out.print(b[i]+" ");
    }
Integrity
  • 34
  • 5