Find Duplicate Item From Given Array

1. First Way to Find.

public class Duplicate {

public static void main(String[] args) {

int []k={1,2,8,2,3,5,4,9};

int index=-1;

for (int i = 0; i < k.length-1; i++)

{

for (int j = i+1; j < k.length; j++)

{

if( (k[i]==k[j]) && (i != j) )

{

index=i;

}

}

}

System.out.println((index!=-1)?"Repeated number is "+k[index]:"no repeat");;


}

}
          ___________________________________________________________________________


 
2. First Way to Find.

import java.util.HashSet;

public class Duplicate {

public static void main(String[] args) {

int []k={1,2,3,6,3,5,8,3,9};

HashSet unique = new HashSet();

for (Integer item : k)

{

if(!unique.add(item))

{

System.out.println("Duplicate Item is : "+item);

}

}

}

}

No comments: