From 4845dae4b352ffabd93ca816ec40cd123e558359 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 2 Aug 2022 22:46:54 +0200 Subject: [PATCH] problems: add kth smallest element in a sorted matrix Signed-off-by: Matej Focko --- ...th-smallest-element-in-a-sorted-matrix.cpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 problems/kth-smallest-element-in-a-sorted-matrix.cpp diff --git a/problems/kth-smallest-element-in-a-sorted-matrix.cpp b/problems/kth-smallest-element-in-a-sorted-matrix.cpp new file mode 100644 index 0000000..42aceed --- /dev/null +++ b/problems/kth-smallest-element-in-a-sorted-matrix.cpp @@ -0,0 +1,52 @@ +#include +#include +#include +#include + +using namespace std; + +class Solution { +public: + int kthSmallest(vector>& matrix, int k) + { + int low = matrix.front().front(); + int high = matrix.back().back(); + + while (low < high) { + int mid = low + (high - low) / 2; + + int rank = 0; + for (const auto& row : matrix) { + rank += upper_bound(row.begin(), row.end(), mid) - row.begin(); + } + + if (rank < k) { + low = mid + 1; + } else { + high = mid; + } + } + + return low; + } +}; + +int main() +{ + Solution s; + + vector> m; + int k; + + m = { + { 1, 5, 9 }, + { 10, 11, 13 }, + { 12, 13, 15 } + }; + k = 8; + assert(s.kthSmallest(m, k) == 13); + + m = { { -5 } }; + k = 1; + assert(s.kthSmallest(m, k) == -5); +}