-
Notifications
You must be signed in to change notification settings - Fork 170
/
Find duplicates in a given array when elements are not limited to a range
60 lines (50 loc) · 1.59 KB
/
Find duplicates in a given array when elements are not limited to a range
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
public class GFG {
// Function to find the Duplicates,
// if duplicate occurs 2 times or
// more than 2 times in
// array so, it will print duplicate
// value only once at output
static void findDuplicates(
int arr[], int len)
{
// initialize ifPresent as false
boolean ifPresent = false;
// ArrayList to store the output
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = 0; i < len - 1; i++) {
for (int j = i + 1; j < len; j++) {
if (arr[i] == arr[j]) {
// checking if element is
// present in the ArrayList
// or not if present then break
if (al.contains(arr[i])) {
break;
}
// if element is not present in the
// ArrayList then add it to ArrayList
// and make ifPresent at true
else {
al.add(arr[i]);
ifPresent = true;
}
}
}
}
// if duplicates is present
// then print ArrayList
if (ifPresent == true) {
System.out.print(al + " ");
}
else {
System.out.print(
"No duplicates present in arrays");
}
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 12, 11, 40, 12, 5, 6, 5, 12, 11 };
int n = arr.length;
findDuplicates(arr, n);
}
}