Java Program to remove duplicate element in an Array

Removing Duplicate elements from array is not difficult, just we have to concentrate on array index. We can remove duplicate elements from array in 2 way: using temporary array or using seperate index. For removing duplicate elements array must be sorted. You can use array.sort() in-built function or seperate programs like Selection Sort or Bubble Sort .

Java Program - Remove Duplicate Elements using Temporary Array

public class RemoveDuplicate1{
    
    public static int RemoveDuplicate(int arr[],int n){
        
        int j=0;
        
        int temp[] = new int [n];
        
        if(n==0 || n==1){
            return n;
        }
        
        for(int i=0; i<n-1;i++){
            if(arr[i]!=arr[i+1]){
                temp[j++] = arr[i];
            }
        }
        
        temp[j++] = arr[n-1]; 
        
        for(int i=0; i<j;i++){
            arr[i] = temp[i];
        }
        
        return j;
        
    }

    public static void main(String []args){
        
        int arr[] = {10, 20, 20, 30, 30, 60, 60, 70, 70};
        
        int length = arr.length;
        
        System.out.println("Without Removing Duplicate");
        
        for(int i: arr){
            System.out.print(i+"  ");
        }
        
        length = RemoveDuplicate(arr, length);
        
        System.out.println("\nAfter Removing Duplicate");
        
        for(int i=0; i<length;i++){
            System.out.print(arr[i]+"  ");
        }
        
     }
}


Java Program - Remove Duplicate Elements Using Separate Index

public class RemoveDuplicate2{
    
    public static int RemoveDuplicateIndex(int arr[],int n){
        
        int j=0;
        
        if(n==0 || n==1){
            return n;
        }
        
        for(int i=0;i<n-1;i++){
            if(arr[i]!=arr[i+1]){
                arr[j++]=arr[i];
            }
        }
        
        arr[j++]=arr[n-1];
        
        return j;
        
    }

    public static void main(String []args){
        
        int arr[] = {10, 20, 20, 30, 30, 60, 60, 70, 70, 90};
        
        int length = arr.length;
        
        System.out.println("Without Removing Duplicate");
        
        for(int i: arr){
            System.out.print(i+"  ");
        }
        
        length = RemoveDuplicateIndex(arr, length);
        
        System.out.println("\nAfter Removing Duplicate");
        
        for(int i=0; i<length;i++){
            System.out.print(arr[i]+"  ");
        }
        
     }
}

Java Program to remove duplicate element in an Array Java Program to remove duplicate element in an Array Reviewed by Huzaif Sayyed on July 04, 2018 Rating: 5

No comments:

Powered by Blogger.