|
Duplicate numbers in an Array
Print the duplicate numbers in a given array.
|
package com.bethecoder.tutorials.coding.examples;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Print the duplicate numbers in a given array.
*/
public class PrintDuplicateNumbersTest {
/**
* @param args
*/
public static void main(String[] args) {
int [] nums = { 1, 2, 22, 1, 3, 4, 6, 2, 8, 9, 22 };
System.out.println("Duplicates in " + Arrays.toString(nums) + " : " + getDuplicateNums(nums));
nums = new int [] { 1, 2, 3, 4 };
System.out.println("Duplicates in " + Arrays.toString(nums) + " : " + getDuplicateNums(nums));
nums = new int [] { 6,6, 4,4,4, 5,5, 8,8,8,8 };
System.out.println("Duplicates in " + Arrays.toString(nums) + " : " + getDuplicateNums(nums));
}
private static List<Integer> getDuplicateNums(int [] nums) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0 ; i < nums.length ; i ++) {
if (map.containsKey(nums[i])) {
map.put(nums[i], map.get(nums[i]) + 1); //duplicate found
} else {
map.put(nums[i], 1); //first time found
}
}
Iterator<Integer> it = map.keySet().iterator();
List<Integer> duplicates = new ArrayList<Integer>();
while (it.hasNext()) {
int num = it.next();
if (map.get(num) > 1) { //duplicate characters
duplicates.add(num);
}
}
return duplicates;
}
}
|
| |
It gives the following output,
Duplicates in [1, 2, 22, 1, 3, 4, 6, 2, 8, 9, 22] : [1, 2, 22]
Duplicates in [1, 2, 3, 4] : []
Duplicates in [6, 6, 4, 4, 4, 5, 5, 8, 8, 8, 8] : [4, 5, 6, 8]
|
|