-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathCommanElements.java
More file actions
33 lines (33 loc) · 959 Bytes
/
CommanElements.java
File metadata and controls
33 lines (33 loc) · 959 Bytes
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
class Solution
{
ArrayList<Integer> commonElements(int A[], int B[], int C[], int n1, int n2, int n3)
{
// code here
// Declare an Array list to store results
ArrayList<Integer> arr = new ArrayList<>();
int i=0,j=0,k=0;
while(i<n1 && j<n2 && k<n3)
{
if(A[i]<B[j]) i++;
else if(A[i]>B[j]) j++;
else
{
// This is for checking duplicacy
if(i>0 && A[i]==A[i-1])
{
i++;
continue;
}
// Now we will search the common element in third array!
// k<n3 avoids array index out of bound exception
while(k<n3 && C[k]<B[j]) k++;
if(k<n3 && C[k]==B[j])
{
arr.add(C[k]);
}
i++;j++;
}
}
return arr;
}
}