Find a duplicate element in the given array of integers. There will be only a single duplicate element in the array.
Note: Do not use any inbuilt functions/libraries for your main logic.
Input Format
First line of input contains size of the array – N and second line contains the elements of the array.
Constraints
2 <= N <= 100
0 <= ar[i] <= 109
Output Format
Print the duplicate element from the given array.
Input | Output |
---|---|
6 5 4 10 9 21 10 | 10 |
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] arr = new int[N];
for (int j = 0; j < N; j++) {
arr[j] = sc.nextInt();
}
sorting(arr);
int duplicate = Duplicates(arr);
System.out.println(duplicate);
}
public static void sorting(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minInd = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minInd]) {
minInd = j;
}
}
if (minInd != i) {
int temp = arr[i];
arr[i] = arr[minInd];
arr[minInd] = temp;
}
}
}
private static int Duplicates(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
if (arr[i] == arr[i + 1]) {
return arr[i];
}
}
return -1;
}
}