forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lucky-numbers-in-a-matrix.cpp
67 lines (64 loc) · 1.97 KB
/
lucky-numbers-in-a-matrix.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Time: O(m * n)
// Space: O(m + n)
class Solution {
public:
vector<int> luckyNumbers (vector<vector<int>>& matrix) {
vector<int> rows;
for (const auto& row : matrix) {
rows.emplace_back(*min_element(row.cbegin(), row.cend()));
}
vector<int> cols;
for (int c = 0; c < matrix[0].size(); ++c) {
int max_cell = 0;
for (int r = 0; r < matrix.size(); ++r) {
max_cell = max(max_cell, matrix[r][c]);
}
cols.emplace_back(max_cell);
}
vector<int> result;
for (int r = 0; r < matrix.size(); ++r) {
for (int c = 0; c < matrix[0].size(); ++c) {
if (rows[r] == cols[c]) {
result.emplace_back(matrix[r][c]);
}
}
}
return result;
}
};
// Time: O(m * n)
// Space: O(m + n)
class Solution2 {
public:
vector<int> luckyNumbers (vector<vector<int>>& matrix) {
unordered_set<int> rows;
for (const auto& row : matrix) {
rows.emplace(*min_element(row.cbegin(), row.cend()));
}
unordered_set<int> cols;
for (int c = 0; c < matrix[0].size(); ++c) {
int max_cell = 0;
for (int r = 0; r < matrix.size(); ++r) {
max_cell = max(max_cell, matrix[r][c]);
}
cols.emplace(max_cell);
}
unordered_set<int> intersection = set_intersection(rows, cols);
return vector<int>(intersection.cbegin(), intersection.cend());
}
private:
template<typename T>
unordered_set<T> set_intersection(const unordered_set<T>& a,
const unordered_set<T>& b) {
if (a.size() > b.size()) {
return set_intersection(b, a);
}
unordered_set<T> result;
for (const auto& x : a) {
if (b.count(x)) {
result.emplace(x);
}
}
return result;
}
};