top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Write a program to remove the duplicate elements in an array and print in java?

+1 vote
2,507 views

Write a program to remove the duplicate elements in an array and print
Eg) Array Elements - 12, 34, 12, 45, 67, 89
O/P: 12,34,45,67,89

posted Apr 22, 2017 by Azhar Keer

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote
 
Best answer
public class MyDuplicateElements {
 public static int[] removeDuplicates(int[] input){

    int j = 0;
    int i = 1;
    //return if the array length is less than 2
    if(input.length < 2){
        return input;
    }
    while(i < input.length){
        if(input[i] == input[j]){
            i++;
        }else{
            input[++j] = input[i++];
        }   
    }
    int[] output = new int[j+1];
    for(int k=0; k<output.length; k++){
        output[k] = input[k];
    }

    return output;
}

public static void main(String a[]){
    int[] input1 = {12, 34, 12, 45, 67, 89};
    int[] output = removeDuplicates(input1);
    for(int i:output){
        System.out.print(i+" ");
    }
 }
}

Output:

12,34,45,67,89

answer May 20, 2017 by Sona Munshi
this logic is not correct...output is same as i given.
See one of the number 12 is not included in the series.
That's right that the simplest code to follow
0 votes
public class MyDuplicateElements {
 public static int[] removeDuplicates(int[] input){

    int j = 0,flag;
    int i = 1;
    //return if the array length is less than 2
    if(input.length < 2){
        return input;
    }
    while(i < input.length){
        flag=0;
        for(int k=0;k<i;k++){
        if(input[i] == input[k]){
            flag=1;
            break;
        }

        }
        if(flag==0)
        {
            input[++j] = input[i];
        } 
         i++;
        }

    int[] output = new int[j+1];
    for(int k=0; k<output.length; k++){
        output[k] = input[k];
    }

    return output;
}

public static void main(String a[]){
    int[] input1 = {12, 34, 12, 45, 67, 89};
    int[] output = removeDuplicates(input1);
    for(int i:output){
        System.out.print(i+" ");
    }
 }
}
answer Jul 8, 2018 by anonymous
Similar Questions
+1 vote

Write a program to print the sum of the elements of the array with the given below condition. If the array has 6 and 7 in succeeding orders, ignore 6 and 7 and the numbers between them for the calculation of sum.
Eg1) Array Elements - 10,3,6,1,2,7,9
O/P: 22
[i.e 10+3+9]
Eg2) Array Elements - 7,1,2,3,6
O/P:19
Eg3) Array Elements - 1,6,4,7,9
O/P:10

+3 votes

Write a program to print the sum of the element of the array with the given below condition?

If the array has 6 and 7 in succeeding orders, ignore 6 and 7 and the numbers between them for the calculation of sum.

Array Elements - 10, 3, 6, 1, 2, 7, 9

Output: 22
i.e 10+3+9

...