top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

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

+1 vote
229 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 Google+ Share Button LinkedIn Share Button Multiple Social 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 by anonymous
Similar Questions
+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

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...