Skip to content

Instantly share code, notes, and snippets.

@pethaniakshay
Last active May 26, 2017 10:00
Show Gist options
  • Save pethaniakshay/3266867ebdbaa206c155157adf9b7b9b to your computer and use it in GitHub Desktop.
Save pethaniakshay/3266867ebdbaa206c155157adf9b7b9b to your computer and use it in GitHub Desktop.
Find Duplicate In Array Soltution.Without recursion and using most simplest way.
import java.util.*;
public class FindDuplicateInArray {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the No of elements: ");
int size =sc.nextInt();
ArrayList<Integer> a = new ArrayList<>();
System.out.println("Enter the array elements: ");
for (int i = 0 ; i< size ; i++){
a.add(i,sc.nextInt());
}
FindDuplicateInArray obj = new FindDuplicateInArray();
System.out.println("Repeated number is: "+ obj.repeatedNumber(a) );
}
public int repeatedNumber(final List<Integer> a) {
int temp= a.size();
int check[] = new int[temp];
int ret;
temp--;
if(a.size()/2 == 0){
for(int i=0 ; i< (a.size()/2) ; i++){
if(check[a.get(i)]==0){
check[a.get(i)]++;
}
else
{
return a.get(i);
}
if(check[a.get(temp)]==0){
check[a.get(temp)]++;
}
else
{
return a.get(temp);
}
temp--;
}
}
else{
for(int i=0 ; i< (a.size()/2)+1 ; i++){
if(check[a.get(i)]==0){
check[a.get(i)]++;
}
else
{
return a.get(i);
}
if(temp != ((a.size()/2)+1)){
if(check[a.get(temp)]==0){
check[a.get(temp)]++;
}
else
{
return a.get(temp);
}
}
temp--;
}
}
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment