forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlongest-common-subsequence-between-sorted-arrays.cpp
53 lines (51 loc) · 1.65 KB
/
longest-common-subsequence-between-sorted-arrays.cpp
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
// Time: O(m * n)
// Space: O(l), l is min(len(arr) for arr in arrays)
class Solution {
public:
vector<int> longestCommomSubsequence(vector<vector<int>>& arrays) {
const auto min_cit = min_element(cbegin(arrays), cend(arrays),
[](const auto& a, const auto& b) {
return size(a) < size(b);
});
vector<int> result = *min_cit;
for (auto cit = cbegin(arrays); cit != cend(arrays); ++cit) {
if (cit == min_cit) {
continue;
}
vector<int> new_result;
for (int i = 0, j = 0; i != size(result) && j != size(*cit);) {
if (result[i] < (*cit)[j]) {
++i;
} else if (result[i] > (*cit)[j]) {
++j;
} else {
new_result.emplace_back(result[i]);
++i;
++j;
}
}
result = move(new_result);
}
return result;
}
};
// Time: O(m * n)
// Space: O(k), k is min(m * n, max(x for arr in arrays for x in arr))
class Solution2 {
public:
vector<int> longestCommomSubsequence(vector<vector<int>>& arrays) {
unordered_map<int, int> lookup;
for (const auto& arr : arrays) {
for (const auto& x : arr) {
++lookup[x];
}
}
vector<int> result;
for (const auto& x : arrays[0]) {
if (lookup[x] == size(arrays)) {
result.emplace_back(x);
}
}
return result;
}
};