Java Interview Questions - Find Duplicate Number in an Array
package com.javastructures;
public class RemovingDuplicateUsingTemporaryArray {
static void removeDuplicates(int arr[]) {
int[] temp = new int[arr.length];
int j = 0;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] != arr[i + 1])
temp[j++] = arr[i];
}
temp[j++] = arr[arr.length - 1];
// Print temporary array
for (int i = 0; i < j; i++)
System.out.print(temp[i] + " ");
}
public static void main(String[] args) {
int inputArray[] = { 1, 2, 2, 3, 4, 4, 4, 5, 5, 6 };
removeDuplicates(inputArray);
}
}
package com.javastructures;
public class RemovingDuplicateWithoutUsingTemporaryArray {
static void removeDuplicates(int arr[]) {
int j = 0;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] != arr[i + 1])
arr[j++] = arr[i];
}
arr[j++] = arr[arr.length - 1];
for (int i = 0; i < j; i++) {
System.out.print(arr[i] + " ");
}
}
public static void main(String[] args) {
int arr[] = { 1, 2, 2, 3, 4, 4, 4, 5, 5 };
removeDuplicates(arr);
}
}