/**
* Find the only duplicate number in an Array.
*/ public class OneDuplicateNumberTest {
/**
* @param args
*/ public static void main(String[] args) {
Integer [] nums = { 1, 2, 3, 4, 6, 6, 7, 8, 9, 10};
System.out.println("Only duplicate element in " +
Arrays.asList(nums) + " is " + getDuplicateNumber(nums));
nums = new Integer [] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 14, 15};
System.out.println("Only duplicate element in " +
Arrays.asList(nums) + " is " + getDuplicateNumber(nums));
//multiple duplicates - should return -1 (invalid condition)
nums = new Integer [] { 1, 2, 2, 3, 4, 4 };
System.out.println("Only duplicate element in " +
Arrays.asList(nums) + " is " + getDuplicateNumber(nums));
}
/**
* Returns the only duplicate number in array.
*
* @param nums
* @return
*/ private static int getDuplicateNumber(Integer [] nums) {
List<Integer> mynums = new ArrayList<Integer>(Arrays.asList(nums));
Set<Integer> uniquenums = new HashSet<Integer>(Arrays.asList(nums));
for (Integer num : uniquenums) {
mynums.remove(num); //Removes only the first occurrence
}
if (mynums.size() == 1) { //should left with only duplicate element return mynums.get(0);
}
return -1;
}
}
It gives the following output,
Only duplicate element in [1, 2, 3, 4, 6, 6, 7, 8, 9, 10] is 6
Only duplicate element in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 14, 15] is 14
Only duplicate element in [1, 2, 2, 3, 4, 4] is -1