-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDuplicates.java
More file actions
68 lines (64 loc) · 1.69 KB
/
Duplicates.java
File metadata and controls
68 lines (64 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package algorithm.search;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* The type Duplicates.
*/
public class Duplicates {
/**
* Find duplicates array list.
*
* @param arr the arr
* @return the array list
*/
public static ArrayList<Integer> findDuplicates(int[] arr) {
ArrayList<Integer> duplicates = new ArrayList<Integer>();
Map<Integer, Integer> map = new HashMap();
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (map.containsKey(arr[i])) {
count = map.get(arr[i]);
map.put(arr[i], count + 1);
} else {
map.put(arr[i], 1);
}
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() > 1) {
duplicates.add(entry.getKey());
}
}
return duplicates;
}
/**
* The entry point of application.
*
* @param args the input arguments
*/
public static void main(String[] args) {
int arr[] = {
7,
5,
4,
3,
5,
11,
7,
11,
3,
11
};
ArrayList<Integer> dupes = findDuplicates(arr);
System.out.println("Duplicates in " + Arrays.toString(arr) + " are " + dupes);
int arr1[] = {
6,
5,
17,
17
};
dupes = findDuplicates(arr1);
System.out.println("Duplicates in " + Arrays.toString(arr1) + " are " + dupes);
}
}