-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
49 lines (40 loc) · 1.04 KB
/
Copy pathsolution.cpp
File metadata and controls
49 lines (40 loc) · 1.04 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
class Solution
{
public:
vector<int> intersection(vector<int> &a, vector<int> &b)
{
vector<int> ans;
int i = 0, j = 0;
int n = a.size(), m = b.size();
while (i < n && j < m)
{
// If current element in a is smaller, move i
if (a[i] < b[j])
{
i++;
}
// If current element in b is smaller, move j
else if (a[i] > b[j])
{
j++;
}
// If both elements are equal
else
{
ans.push_back(a[i]);
int current = a[i];
// Skip duplicates in array a
while (i < n && a[i] == current)
{
i++;
}
// Skip duplicates in array b
while (j < m && b[j] == current)
{
j++;
}
}
}
return ans;
}
};