/
1337. The K Weakest Rows in a Matrix 5.cpp
57 lines (46 loc) · 1.22 KB
/
1337. The K Weakest Rows in a Matrix 5.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
// https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/
class Solution
{
private:
struct Comparator
{
bool operator()(pair<int, int> &firstRow, pair<int, int> &secondRow)
{
if (firstRow.first == secondRow.first)
return firstRow.second > secondRow.second;
return firstRow.first > secondRow.first;
}
};
public:
vector<int> kWeakestRows(vector<vector<int>> &mat, int k)
{
vector<int> result;
priority_queue<pair<int, int>, vector<pair<int, int>>, Comparator> minHeap;
int i = 0;
for (vector<int> &row : mat)
{
int numOnes = binarySearch(row);
minHeap.push({numOnes, i++});
}
while (k--)
{
result.push_back(minHeap.top().second);
minHeap.pop();
}
return result;
}
int binarySearch(vector<int> &row)
{
int left = 0;
int right = row.size() - 1;
while (left <= right)
{
int middle = left + (right - left) / 2;
if (row[middle] == 0)
right = middle - 1;
else
left = middle + 1;
}
return left;
}
};