forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
find-smallest-common-element-in-all-rows.cpp
40 lines (38 loc) · 1.19 KB
/
find-smallest-common-element-in-all-rows.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
// Time: O(m * n)
// Space: O(n)
class Solution {
public:
int smallestCommonElement(vector<vector<int>>& mat) {
// values could be duplicated in each row
unordered_set<int> intersections(mat[0].cbegin(), mat[0].cend());
for (int i = 1; i < mat.size(); ++i) {
const auto a = move(intersections);
const unordered_set<int> b(mat[i].cbegin(), mat[i].cend());
copy_if(a.cbegin(), a.cend(),
inserter(intersections, intersections.begin()),
[&b](const int x){ return b.count(x); });
if (intersections.empty()) {
return -1;
}
}
return *min_element(intersections.cbegin(), intersections.cend());
}
};
// Time: O(m * n)
// Space: O(n)
class Solution2 {
public:
int smallestCommonElement(vector<vector<int>>& mat) {
// assumed value is unique in each row
unordered_map<int, int> counter;
for (const auto& row : mat) {
for (const auto& c : row) {
++counter[c];
if (counter[c] == mat.size()) {
return c;
}
}
}
return -1;
}
};