// C++ typedef tuple<int, int, int> Tuple; intkthSmallest(vector<vector<int>>& matrix, int k){ int N = (int)matrix.size(); auto cmp = [](Tuple& t1, Tuple& t2) { return get<2>(t1) > get<2>(t2); }; priority_queue<Tuple, vector<Tuple>, decltype(cmp)> pq(cmp); for (int i = 0; i < N; ++i) { pq.push({0, i, matrix[0][i]}); } for (int i = 0; i < k - 1; ++i) { auto t = pq.top(); pq.pop(); if (get<0>(t) == N - 1) { continue; } int x, y, val; tie(x, y, val) = t; pq.push({x + 1, y, matrix[x+1][y]}); } return get<2>(pq.top()); }
// C++ intkthSmallest(vector<vector<int>>& matrix, int k){ int N = (int)matrix.size(); int lo = matrix[0][0]; int hi = matrix[N-1][N-1] + 1; // [lo, hi) while (lo < hi) { int mid = lo + (hi - lo)/2; int count = 0; int j = N - 1; for (int i = 0; i < N; ++i) { while (j >= 0 && matrix[i][j] > mid) { --j; } count += (j + 1); } if (count < k) { lo = mid + 1; } else { hi = mid; } } return lo; }