-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC0378.cpp
More file actions
executable file
·36 lines (32 loc) · 768 Bytes
/
LC0378.cpp
File metadata and controls
executable file
·36 lines (32 loc) · 768 Bytes
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
/*
Problem Statement: https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/
Time: O(m • log n)
Space: O(1)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int m, n, low, high;
m = matrix.size();
n = matrix[0].size();
low = matrix[0][0];
high = matrix[m - 1][n - 1];
// helper function
auto count = [&](int x) {
int cnt = 0;
for (int i = 0; i < m; i++)
cnt += distance(matrix[i].begin(), upper_bound(matrix[i].begin(), matrix[i].end(), x));
return cnt;
};
// binary search
while (low < high) {
int mid = low + (high - low) / 2;
if (count(mid) < k)
low = mid + 1;
else
high = mid;
}
return low;
}
};