Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates from integer array

Tags:

java

arrays

I having a problem with coding this:

Write a static method named removeDuplicates that takes as input an array of integers and returns as a result a new array of integers with all duplicates removed. For example, if the input array has the elements {4, 3, 3, 4, 5, 2, 4} the resulting array should be {4, 3, 5, 2}

Here's what I have done so far

public static int[] removeDuplicates(int []s){
    int [] k = new int[s.length];
    k[0]=s[0];
    int m =1;
    for(int i=1;i<s.length;++i){
        if(s[i]!=s[i-1]){
            k[m]=s[i];
            ++m;
        }//endIF
    }//endFori
    return k;
}//endMethod
like image 477
Ali-J8 Avatar asked Dec 17 '12 10:12

Ali-J8


5 Answers

I have found this solution to this problem. Using HashSet is a powerful way to filter and order an array of integers. It is very fast as well.

I have written this short code in order to show the power of this feature. From an array of integers, it creates two lists. One with the ordered integers without the duplicates and the other which shows only the duplicates and the number of times they are in the initial array.

public class DuplicatesFromArray {

    public static void main(String args[]) {
        int[] withDuplicates = { 1, 2, 3, 1, 2, 3, 4, 5, 3, 6 };
        
        
        // complexity of this solution is O[n]

        duplicates(withDuplicates);

        
    }

//Complexity of this method is O(n)
    
    public static void duplicates(int[] input) {

        HashSet<Integer> nums = new HashSet<Integer>();

        List<Integer> results = new ArrayList<Integer>();
        List<Integer> orderedFiltered = new ArrayList<Integer>();

        for (int in : input) {

            if (nums.add(in) == false) {
                results.add(in);
            } else {
                orderedFiltered.add(in);
            }
        }
        out.println(
                "Ordered and filtered elements found in the array are : " + Arrays.toString(orderedFiltered.toArray()));
        out.println("Duplicate elements found in the array are : " + Arrays.toString(results.toArray()));
    }

    
    /**
     * Generic method to find duplicates in array. Complexity of this method is O(n)
     * because we are using HashSet data structure.
     * 
     * @param array
     * @return
     */
    public static <T extends Comparable<T>> void getDuplicates(T[] array) {
        Set<T> dupes = new HashSet<T>();
        for (T i : array) {
            if (!dupes.add(i)) {
                System.out.println("Duplicate element in array is : " + i);
            }
        }

    }

}
like image 72
SGuirous Avatar answered Oct 24 '22 05:10

SGuirous


To Preserve the ordering and to remove duplicates in the integer array, you can try this:

public void removeDupInIntArray(int[] ints){
    Set<Integer> setString = new LinkedHashSet<Integer>();
    for(int i=0;i<ints.length;i++){
        setString.add(ints[i]);
    }
    System.out.println(setString);
}

Hope this helps.

like image 40
buddy24 Avatar answered Nov 11 '22 22:11

buddy24


try this -

public static int[] removeDuplicates(int []s){
    int result[] = new int[s.length], j=0;
    for (int i : s) {
        if(!isExists(result, i))
            result[j++] = i;
    }
    return result;
}

private static boolean isExists(int[] array, int value){
    for (int i : array) {
        if(i==value)
            return true;
    }
    return false;
}
like image 6
Subhrajyoti Majumder Avatar answered Nov 11 '22 22:11

Subhrajyoti Majumder


First of all, you should know length without duplicates(dups): initial length minus number of dups. Then create new array with right length. Then check each element of list[] for dups, if dup founded - check next element, if dup not founded - copy element to new array.

public static int[] eliminateDuplicates(int[] list) {
    int newLength = list.length;
    // find length w/o duplicates:
    for (int i = 1; i < list.length; i++) {
        for (int j = 0; j < i; j++) {
            if (list[i] == list[j]) {   // if duplicate founded then decrease length by 1
                newLength--;
                break;
            }
        }
    }

    int[] newArray = new int[newLength]; // create new array with new length
    newArray[0] = list[0];  // 1st element goes to new array
    int inx = 1;            // index for 2nd element of new array
    boolean isDuplicate;

    for (int i = 1; i < list.length; i++) {
        isDuplicate = false;
        for (int j = 0; j < i; j++) {
            if (list[i] == list[j]) {  // if duplicate founded then change boolean variable and break
                isDuplicate = true;
                break;
            }
        }
        if (!isDuplicate) {     // if it's not duplicate then put it to new array
            newArray[inx] = list[i];
            inx++;
        }
    }
    return newArray;
}
like image 3
Otto Kocebu Avatar answered Nov 11 '22 22:11

Otto Kocebu


Maybe you can use lambdaj (download here,website), this library is very powerfull for managing collections (..list,arrays), the following code is very simple and works perfectly:

import static ch.lambdaj.Lambda.selectDistinct;
import java.util.Arrays;
import java.util.List;

public class DistinctList {
     public static void main(String[] args) {
         List<Integer> numbers =  Arrays.asList(1,3,4,2,1,5,6,8,8,3,4,5,13);
         System.out.println("List with duplicates: " + numbers);
         System.out.println("List without duplicates: " + selectDistinct(numbers));
     }
}

This code shows:

List with duplicates: [1, 3, 4, 2, 1, 5, 6, 8, 8, 3, 4, 5, 13]
List without duplicates: [1, 2, 3, 4, 5, 6, 8, 13]

In one line you can get a distinct list, this is a simple example but with this library you can resolve more.

selectDistinct(numbers)

You must add lambdaj-2.4.jar to your project. I hope this will be useful.

Note: This will help you assuming you can have alternatives to your code.

like image 2
Gaston Flores Avatar answered Nov 11 '22 22:11

Gaston Flores