-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathArray-Common-elements
More file actions
77 lines (63 loc) · 1.93 KB
/
Array-Common-elements
File metadata and controls
77 lines (63 loc) · 1.93 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
69
70
71
72
73
74
75
76
77
class Solution
{
ArrayList<Integer> commonElements(int A[], int B[], int C[], int n1, int n2, int n3)
{
// ArrayList <Integer> arr = new ArrayList<>();
// This Apperoch fails because when your array is A[3,3,1] , B[3,6,7],C[9,8,7]
// it will also show result true so we can't use this aaproch
// Map <Integer,Integer> map = new LinkedHashMap<>();
// for(int i=0;i<A.length;i++){
// if(map.containsKey(A[i])){
// map.put(A[i],map.get(A[i])+1);
// }else{
// map.put(A[i],1);
// }
// }
// for(int i=0;i< B.length;i++){
// if(map.containsKey(B[i])){
// map.put(B[i],map.get(B[i])+1);
// }
// else{
// map.put(B[i],1);
// }
// }
// for(int i : C){
// if(map.containsKey(i)){
// map.put(i,map.getOrDefault(i, 0)+1);
// }
// else{
// map.put(i,1);
// }
// }
// for(int i : map.keySet()){
// if(map.get(i) == 3){
// arr.add(i);
// }
// // System.out.println(i);
// }
// return arr;
ArrayList <Integer> arr = new ArrayList<>();
int i=0;
int j=0;
int k=0;
while(i<n1 && j<n2 && k<n3){
if(A[i]== B[j] && B[j] == C[k]){
if(!arr.contains(A[i])){
arr.add(A[i]);
}
i++;
j++;
k++;
}else{
if(A[i] <B[j]){
i++;
}else if(B[j]<C[k]){
j++;
}else{
k++;
}
}
}
return arr;
}
}