forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
the-k-weakest-rows-in-a-matrix.cpp
123 lines (114 loc) · 3.33 KB
/
the-k-weakest-rows-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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// Time: O(m * n)
// Space: O(k)
class Solution {
public:
vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
vector<int> result;
unordered_set<int> lookup;
for (int j = 0; j < mat[0].size(); ++j) {
for (int i = 0; i < mat.size(); ++i) {
if (mat[i][j] || lookup.count(i)) {
continue;
}
lookup.emplace(i);
result.emplace_back(i);
if (result.size() == k) {
return result;
}
}
}
for (int i = 0; i < mat.size(); ++i) {
if (lookup.count(i)) {
continue;
}
lookup.emplace(i);
result.emplace_back(i);
if (result.size() == k) {
break;
}
}
return result;
}
};
// Time: O(m * n)
// Space: O(k)
class Solution2 {
public:
vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
OrderedDict<int, bool> lookup;
for (int j = 0; j < mat[0].size(); ++j) {
for (int i = 0; i < mat.size(); ++i) {
if (mat[i][j] || lookup.count(i)) {
continue;
}
lookup[i] = true;
if (lookup.size() == k) {
return lookup.keys();
}
}
}
for (int i = 0; i < mat.size(); ++i) {
if (lookup.count(i)) {
continue;
}
lookup[i] = true;
if (lookup.size() == k) {
break;
}
}
return lookup.keys();
}
private:
template<typename K, typename V>
class OrderedDict {
public:
bool count(const K& key) const {
return map_.count(key);
}
V& operator[](const K& key) {
if (!map_.count(key)) {
list_.emplace_front();
list_.begin()->first = key;
map_[key] = list_.begin();
}
return map_[key]->second;
}
void popitem() {
auto del = list_.front(); list_.pop_front();
map_.erase(del.first);
}
vector<K> keys() const {
vector<K> result;
transform(list_.crbegin(), list_.crend(), back_inserter(result),
[](const auto& x) {
return x.first;
});
return result;
}
int size() const {
return list_.size();
}
private:
list<pair<K, V>> list_;
unordered_map<K, typename list<pair<K, V>>::iterator> map_;
};
};
// Time: O(m * n + klogk)
// Space: O(m)
class Solution3 {
public:
vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
vector<pair<int, int>> nums;
for (int i = 0; i < mat.size(); ++i) {
nums.emplace_back(accumulate(mat[i].cbegin(), mat[i].cend(), 0), i);
}
nth_element(nums.begin(), nums.begin() + k, nums.end());
sort(nums.begin(), nums.begin() + k);
vector<int> result;
transform(nums.cbegin(), nums.cbegin() + k, back_inserter(result),
[](const auto& x) {
return x.second;
});
return result;
}
};