-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
118 lines (101 loc) · 2.83 KB
/
main.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
class Solution {
struct Row {
vector<int>::iterator it, end;
};
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
auto cmp = [&](Row b, Row a) -> bool { return *a.it < *b.it; };
priority_queue<Row, vector<Row>, decltype(cmp)> pq(cmp);
for (auto& row : matrix) pq.push({row.begin(), row.end()});
while (--k) {
auto row = pq.top();
pq.pop();
row.it = next(row.it);
if (row.it != row.end) pq.push(row);
}
return *pq.top().it;
}
};
class Solution {
struct Row {
vector<int>::iterator it, end;
};
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
auto comp = [&](Row a, Row b) -> bool { return *a.it > *b.it; };
priority_queue<Row, vector<Row>, decltype(comp)> q(comp);
for (auto& r : matrix) q.push({r.begin(), r.end()});
while (--k) {
auto r = q.top();
q.pop();
if (++r.it != r.end) q.push(r);
}
return *q.top().it;
}
};
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int n = matrix.size();
auto countLessThanEqualTo = [&](int t) -> int {
int result = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (matrix[i][j] < t) ++result;
}
}
return result;
};
int l = matrix.front().front();
int r = matrix.back().back();
while (l <= r) {
int m = l + (r - l) / 2;
if (countLessThanEqualTo(m) < k) {
l = m + 1;
} else {
r = m - 1;
}
}
return r;
}
};
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int l = matrix.front().front();
int r = matrix.back().back();
while (l <= r) {
int m = l + (r - l) / 2;
int cnt = 0;
for (const auto vec : matrix) {
cnt += upper_bound(vec.begin(), vec.end(), m) - vec.begin();
}
if (cnt < k) {
l = m + 1;
} else {
r = m - 1;
}
}
return l;
}
};
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int l = matrix.front().front() - 1;
int r = matrix.back().back() + 1;
while (r - l > 1) {
int m = l + (r - l) / 2;
int cnt = 0;
for (const auto vec : matrix) {
cnt += upper_bound(vec.begin(), vec.end(), m) - vec.begin();
}
if (cnt < k) {
l = m;
} else {
r = m;
}
}
return r;
}
};