-
Notifications
You must be signed in to change notification settings - Fork 122
/
Copy path1337. The K Weakest Rows in a Matrix.cpp
100 lines (83 loc) · 2.4 KB
/
1337. 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
// 1337.✅ The K Weakest Rows in a Matrix
class Solution
{
public:
vector<int> Weakest(vector<vector<int>> &mat, int k)
{
// no of rows;
int n = mat.size();
// set is to store pairs of count and index
// count of 1 in ith row, {count,index};
set<pair<int, int>> s;
// set will automatically sort the pair {count, index} in ascending order.
for (int i = 0; i < n; ++i)
{
// stl function for counting frequency of 1 in current row
int cnt = count(mat[i].begin(), mat[i].end(), 1);
// inserting cnt and index pair to set
s.insert({cnt, i});
}
vector<int> ans;
// first k weakest row is our answer
for (auto i : s)
{
if (k == 0)
break;
ans.push_back(i.second);
--k;
}
return ans;
}
vector<int> kWeakestRows(vector<vector<int>> &mat, int k)
{
return Weakest(mat, k);
}
// for github repository link go to my profile.
};
// ANOTHER APPROACH
class Solution
{
public:
// for calculating the soldier using binary search
int binary(vector<int> m)
{
int l = 0;
int h = m.size() - 1;
while (l <= h)
{
int mid = l + (h - l) / 2;
if (m[mid] == 0)
h = mid - 1;
else
l = mid + 1;
}
return l;
}
vector<int> kWeakestRows(vector<vector<int>> &mat, int k)
{
// a binary heap which will maintain pair of count and index {count,index}
priority_queue<pair<int, int>> pq;
vector<int> ans;
for (int i = 0; i < mat.size(); ++i)
{
// calularing cnt of soldier
int cnt = binary(mat[i]);
// instead of using binary func for calculating cnt of 1
// we can use this stl count function
// int cnt = count(mat[i].begin(),mat[i].end(),1);
pq.push(make_pair(cnt, i));
// we need to maintain top k smallest elements
if (pq.size() > k)
pq.pop();
}
// making answer vector
for (int i = 0; i < k; ++i)
{
ans.push_back(pq.top().second);
pq.pop();
}
reverse(ans.begin(), ans.end());
return ans;
}
// for github repository link go to my profile.
};