package com.bruce.test;
public class TestApp {
public static void main(String[] args) {
int[] arr = { 2, 1, 3, 4, 11, 2, 6, 1, 12, 4, 11, 2, 12, 11, 11 };
System.out.println("O(n) space");
OnFindDuplicate(arr);
System.out
.println("\nO(1) space, but duplicated output sometimes like
11");
OoneFindDuplicate(arr);
System.out.println("\nO(1) space, no duplicated output ");
OoneFindDuplicate2(arr);
}
// need a new array as a counter
public static void OnFindDuplicate(int[] arr) {
int[] counter = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
counter[arr[i]]++;
if (counter[arr[i]] == 2) {
System.out.print(arr[i] + ",");
}
}
}
// when you are trying to exchange a number to the right place and find
// already one there, the number is duplicate
public static void OoneFindDuplicate(int[] arr) {
int temp = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != i && arr[arr[i]] != arr[i]) {
temp = arr[arr[i]];
arr[arr[i]] = arr[i];
arr[i] = temp;
} else if (arr[i] != i && arr[arr[i]] == arr[i]) {
System.out.print(arr[i] + ",");
}
}
}
// input array itself can be used as a counter
public static void OoneFindDuplicate2(int[] arr) {
int temp = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == i) {
arr[i] = -1;
} else if (arr[i] >= 0 && arr[arr[i]] == arr[i]) {
System.out.print(arr[i] + ",");
arr[arr[i]] = -2;
} else if (arr[i] >= 0 && arr[arr[i]] >= 0) {
temp = arr[arr[i]];
arr[arr[i]] = -1;
arr[i] = temp;
} else if (arr[i] >= 0 && arr[arr[i]] < 0) {
if (arr[arr[i]] == -1)
System.out.print(arr[i] + ",");
arr[arr[i]] = arr[arr[i]] - 1;
}
}
}
}