IQ

Ad SpeedyAds

Friday, February 10, 2012

Java program To remove duplicates from an array of integers so that each number may appear only once

// to delete the duplicates in n array so that a number may appear only once in the array import java.io.*;
class remDup
{
    public static void main(String args[]) throws IOException
    {
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       System.out.print("Enter the length of the array: ");
       int l=Integer.parseInt(br.readLine());
       int[]a=new int[l];
       for(int i=0; i<l; i++)
        {
          System.out.print("Enter the element number "+(i+1)+" of the array: ");
          a[i]=Integer.parseInt(br.readLine());
         }
      
      //now the real work begins
       
       for(int i=0; i<l; i++)
       {
           for(int j=i+1; j<l; j++)
          {
             while(a[i]==a[j])
             {
                for(int A=j; A<l-1; A++)
                 a[A]=a[A+1];
                 l--;
              }
           }
         }
// real work is done now!!!!

for(int i=0; i<l; i++)
        {
          System.out.println(a[i]);
        }
}// end of main
}// end of class
      
 

12 comments:

  1. i found ArrayIndexOutOfBoundException from above program.
    please reply me....

    ReplyDelete
    Replies
    1. Can you tell me the input for which you got that error?

      Delete
    2. Just make this correction in the code:

      while(a[i]==a[j] && j<l)

      And it shall work fine.

      [Right now it's only "while(a[i]==a[j])" ]

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. int a[] = {6,6,6,3,0,2,2, 25, 35, 25}; for this getting array index out of bound.

    ReplyDelete
  4. May i know what would be the time and space complexity of the above logic..

    ReplyDelete
    Replies
    1. I think the time complexity must be of the order of n² in average cases.
      The inner most while loop may not run more than once in the best case.
      I think we can safely say it's of the order of n².

      I have no idea about the measures of space complexity.

      Delete
  5. can u please explain as to why are we decrementing the value of l inside the inner while loop??

    ReplyDelete
  6. quite helpful....ty :) i used it to get a diffrent result

    ReplyDelete