Open azl397985856 opened 2 years ago
title: "Day 89 378. 有序矩阵中第 K 小的元素" date: 2021-12-07T08:38:44+08:00 tags: ["Leetcode", "c++", "unordered_map"] categories: ["91-day-algorithm"] draft: true
给你一个 n x n 矩阵 matrix ,其中每行和每列元素均按升序排序,找到矩阵中第 k 小的元素。
请注意,它是 排序后 的第 k 小元素,而不是第 k 个 不同 的元素。
示例 1:
输入:matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
输出:13
解释:矩阵中的元素为 [1,5,9,10,11,12,13,13,15],第 8 小元素是 13
示例 2:
输入:matrix = [[-5]], k = 1
输出:-5
提示:
n == matrix.length
n == matrix[i].length
1 <= n <= 300
-109 <= matrix[i][j] <= 109
题目数据 保证 matrix 中的所有行和列都按 非递减顺序 排列
1 <= k <= n^2
- 1、题目中最合适的办法理应是二分的思想。
class Solution {
public:
bool check(vector<vector<int>>& matrix, int mid, int k, int n) {
int i = n - 1, j = 0, num = 0;
while (i >= 0 && j < n)
{
if (matrix[i][j] <= mid)
{
num += i + 1;
j++;
} else i--;
}
return num >= k;
}
int kthSmallest(vector<vector<int>>& matrix, int k) {
int n = matrix.size();
int l = matrix[0][0], r = matrix[n - 1][n - 1];
while(l < r)
{
int mid = l + ((r - l) >> 1);
if (check(matrix, mid, k, n)) r = mid;
else l = mid + 1;
}
return l;
}
};
class Solution {
public int kthSmallest(int[][] matrix, int k) {
int n = matrix.length;
int left = matrix[0][0];
int right = matrix[n - 1][n - 1];
while (left < right) {
int mid = left + ((right - left) >> 1);
if (check(matrix, mid, k, n)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
public boolean check(int[][] matrix, int mid, int k, int n) {
int i = n - 1;
int j = 0;
int num = 0;
while (i >= 0 && j < n) {
if (matrix[i][j] <= mid) {
num += i + 1;
j++;
} else {
i--;
}
}
return num >= k;
}
}
优先队列
class Solution { public int kthSmallest(int[][] matrix, int k) { PriorityQueue<int[]> pq = new PriorityQueue<int[]>(new Comparator<int[]>() { public int compare(int[] a, int[] b) { return a[0] - b[0]; } }); int n = matrix.length; for (int i = 0; i < n; i++) { pq.offer(new int[]{matrix[i][0], i, 0}); } for (int i = 0; i < k - 1; i++) { int[] now = pq.poll(); if (now[2] != n - 1) { pq.offer(new int[]{matrix[now[1]][now[2] + 1], now[1], now[2] + 1}); } } return pq.poll()[0]; } }
时间复杂度:O(klogn),归并 k 次,每次堆中插入和弹出的操作时间复杂度均为logn。
空间复杂度:O(n),堆的大小始终为 n。
主要使用二分的思想
class Solution { public int kthSmallest(int[][] matrix, int k) { int n = matrix.length; int left = matrix[0][0]; int right = matrix[n - 1][n - 1]; while (left < right) { int mid = left + ((right - left) >> 1); if (check(matrix, mid, k, n)) { right = mid; } else { left = mid + 1; } } return left; } public boolean check(int[][] matrix, int mid, int k, int n) { int i = n - 1; int j = 0; int num = 0; while (i >= 0 && j < n) { if (matrix[i][j] <= mid) { num += i + 1; j++; } else { i--; } } return num >= k; } }
时间复杂度:O(logn)
空间复杂度:O(1)
int kthSmallest(vector<vector<int>>& matrix, int k) {
priority_queue<int, vector<int>, greater<int>> q;
for (int i = 0; i < matrix.size(); ++i)
{
for (int j = 0; j < matrix.front().size(); ++j)
{
q.emplace(matrix[i][j]);
}
}
for (; k > 1; --k){
q.pop();
}
return q.top();
}
class Solution {
public:
bool check(vector<vector<int>>& matrix, int mid, int k, int n) {
int i = n - 1;
int j = 0;
int num = 0;
while (i >= 0 && j < n) {
if (matrix[i][j] <= mid) {
num += i + 1;
j++;
} else {
i--;
}
}
return num >= k;
}
int kthSmallest(vector<vector<int>>& matrix, int k) {
int n = matrix.size();
int left = matrix[0][0];
int right = matrix[n - 1][n - 1];
while (left < right) {
int mid = left + ((right - left) >> 1);
if (check(matrix, mid, k, n)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
};
时间复杂度:O(NLogN)
空间复杂度:O(1)
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
n = len(matrix)
def check(mid):
i, j = n - 1, 0
num = 0
while i >= 0 and j < n:
if matrix[i][j] <= mid:
num += i + 1
j += 1
else:
i -= 1
return num >= k
left, right = matrix[0][0], matrix[-1][-1]
while left < right:
mid = (left + right) // 2
if check(mid):
right = mid
else:
left = mid + 1
return left
二分查找
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
n = len(matrix)
def check(mid):
i, j = n - 1, 0
num = 0
while i >= 0 and j < n:
if matrix[i][j] <= mid:
num += i + 1
j += 1
else:
i -= 1
return num >= k
left, right = matrix[0][0], matrix[-1][-1]
while left < right:
mid = (left + right) // 2
if check(mid):
right = mid
else:
left = mid + 1
return left
相当于多列list 求第k小个数 就是用heap 存每一行的head
import heapq
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
"""
heap
"""
heap = [(array[0], index, 0) for index, array in enumerate(matrix)]
heapq.heapify(heap)
for _ in range(k):
num, row, col = heapq.heappop(heap)
if col < len(matrix[row]) - 1:
heapq.heappush(heap, (matrix[row][col + 1], row, col + 1))
return num
时间复杂度O(n +klgn)
空间复杂度O(n)
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: n = len(matrix)
def check(mid):
i, j = n - 1, 0
num = 0
while i >= 0 and j < n:
if matrix[i][j] <= mid:
num += i + 1
j += 1
else:
i -= 1
return num >= k
left, right = matrix[0][0], matrix[-1][-1]
while left < right:
mid = (left + right) // 2
if check(mid):
right = mid
else:
left = mid + 1
return left
思路:二分
class Solution {
//2.二分查找
public int kthSmallest(int[][] matrix, int k) {
int n = matrix.length;
int left = matrix[0][0];
int right = matrix[n - 1][n - 1];
//循环条件是 left < right 因为第k小元素一定存在,
//所以当left == right时就是找到了想要的值了;如果是left <= right的话循环是无法终止的
while(left < right){
int mid = left + (right - left) / 2;
//若不大于中间值mid的数大于等于k,说明mid可能取大了,因此令right = mid
if(getCount(mid, n, matrix) >= k){
right = mid;
}
//若不大于中间值mid的数比k少,说明mid取小了,令left = mid + 1
else{
left = mid + 1;
}
}
return left;
}
//有点像剑指offer.04和240 从左下角开始找
public int getCount(int mid, int n, int[][] matrix){
int i = n - 1, j = 0;
int count = 0;
while(i >= 0 && j < n){
//当这个点小于mid 说明这个点同列以上的所有点都小于mid,可以计数,同时列向右加一
if(matrix[i][j] <= mid){
count += i + 1;
j++;
}
//如果大于了mid,这一行右侧的都大于mid,上移一行
else{
i--;
}
}
return count;
}
}
时间复杂度:O(NLogN) 空间复杂度:O(1)
bool check(int **matrix, int mid, int k, int n) {
int i = n - 1;
int j = 0;
int num = 0;
while (i >= 0 && j < n) {
if (matrix[i][j] <= mid) {
num += i + 1;
j++;
} else {
i--;
}
}
return num >= k;
}
int kthSmallest(int **matrix, int matrixSize, int *matrixColSize, int k) {
int left = matrix[0][0];
int right = matrix[matrixSize - 1][matrixSize - 1];
while (left < right) {
int mid = left + ((right - left) >> 1);
if (check(matrix, mid, k, matrixSize)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
javascript
/*
* @lc app=leetcode.cn id=378 lang=javascript
*
* [378] 有序矩阵中第 K 小的元素
*/
// @lc code=start
/**
* @param {number[][]} matrix
* @param {number} k
* @return {number}
*/
var kthSmallest = function(matrix, k) {
const n = matrix.length
let low = matrix[0][0]
let high = matrix[n - 1][n - 1]
while (low <= high) {
let midVal = low + ((high - low) >>> 1) // 获取中间值
let count = countInMatrix(matrix, midVal) // 找出矩阵中小于等于它的个数
if (count < k) {
low = midVal + 1
} else {
high = midVal - 1
}
}
return low
};
const countInMatrix = (matrix, midVal) => {
const n = matrix.length // 矩阵是 n行n列
let count = 0
let row = 0 // 第一行
let col = n - 1 // 最后一列
while (row < n && col >= 0) {
if (midVal >= matrix[row][col]) { // 大于等于当前行的最右
count += col + 1 // 不大于它的数增加col + 1个
row++ // 比较下一行
} else { // 干不过当前行的最右元素
col-- // 留在当前行,比较左边一个
}
}
return count
};
// @lc code=end
import heapq
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
l = []
element = -1
for i in range(len(matrix)):
heapq.heappush(l, (matrix[i][0], i, 0))
for i in range(k):
element, row, column = heapq.heappop(l)
if column + 1 < len(matrix[row]): heapq.heappush(l, (matrix[row][column + 1], row, column + 1))
return element
时间复杂度:O(n * log(r - l)),二分查找进行次数为O(log(r−l)),每次操作时间复杂度为O(n)。 空间复杂度:O(1),常数空间
class Solution {
public:
bool check(vector<vector<int>>& m, int k, int n, int mid) {
int i = n - 1;
int j = 0;
int cnt = 0;
while (i >= 0 && j < n) {
if (m[i][j] <= mid) {
cnt += i + 1;
j++;
} else {
i--;
}
}
return cnt >= k;
}
int kthSmallest(vector<vector<int>>& matrix, int k) {
int n = matrix.size();
int l = matrix[0][0];
int r = matrix[n - 1][n - 1];
while (l < r) {
int mid = l + (r - l) / 2;
if (check(matrix, k, n, mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
};
class Solution {
public int kthSmallest(int[][] matrix, int k) {
int rows = matrix.length, columns = matrix[0].length;
int[] sorted = new int[rows * columns];
int index = 0;
for (int[] row : matrix) {
for (int num : row) {
sorted[index++] = num;
}
}
Arrays.sort(sorted);
return sorted[k - 1];
}
}
# Understand:
Given an n x n matrix where each of the rows and columns are sorted in ascending order
it is the kth smallest element in the sorted order, not the kth distinct element
n == matrix.length
n == matrix[i].length
1 <= n <= 300
-10^9 <= matrix[i][j] <= 10^9
All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order.
1 <= k <= n^2, k is always valid
k is 1-indexed
matrix =
[[1,5,9],
[10,11,13],
[12,13,15]]
-> 13
matrix = [[-5]], k = 1
-> -5
# Plan & Match:
# Bruteforce:
add all to minheap, poll k times
O(n^2 * log(n ^ 2)) + O(klog(n^2))
-> O(n^2 * log(n ^ 2))
# Optimization:
add head to each row into min heap, poll() once (in total we poll k times), add 1 element from the same row
corner case: a row can be used up earlier
How to have n pointers to each row?
when insert into the heap, insert an object, [value, rowIndex, colIndex]
rewrite the comparator
class Solution {
class Wrapper {
int val;
int rowIndex;
int colIndex;
Wrapper(int val, int rowIndex, int colIndex) {
this.val = val;
this.rowIndex = rowIndex;
this.colIndex = colIndex;
}
}
public int kthSmallest(int[][] matrix, int k) {
// edge case
if (matrix.length == 1) return matrix[0][0];
int n = matrix.length;
PriorityQueue<Wrapper> minHeap = new PriorityQueue<>((a, b) -> (a.val - b.val));
// pre-processing
for (int row = 0; row < n; row++) {
minHeap.offer(new Wrapper(matrix[row][0], row, 0));
}
while (k > 1) {
k -= 1;
Wrapper cur = minHeap.poll();
int curRow = cur.rowIndex;
int curCol = cur.colIndex;
// edge case, nothing to use on the same row
if (curCol == n - 1) {
continue;
} else {
minHeap.offer(new Wrapper(matrix[curRow][curCol + 1], curRow, curCol + 1));
}
}
return minHeap.poll().val;
}
}
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
l = []
element = -1
for i in range(len(matrix)):
heapq.heappush(l, (matrix[i][0], i, 0))
for i in range(k):
element, row, column = heapq.heappop(l)
if column + 1 < len(matrix[row]): heapq.heappush(l, (matrix[row][column + 1], row, column + 1))
return element
C++ Code:
class Solution {
public:
bool findnum(vector<vector<int>> matrix,int n,int mid,int k)
{
int i = 0, j = n - 1;
int ans = 0;
while(i<n&&j>=0)
{
if(matrix[j][i]>mid)
{
--j;
}
else
{
++i;
ans += j+1;
}
}
return ans >= k;
}
int kthSmallest(vector<vector<int>>& matrix, int k) {
int n = matrix.size();
int left = matrix[0][0], right = matrix[n-1][n-1];
while(left<right)
{
int mid = left+((right-left)>>1);
if(findnum(matrix, n, mid, k))
right = mid;
else
left = mid+1;
}
return left;
}
};
Basic idea is binary search in 2D matrix.
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
N = len(matrix)
left, right = matrix[0][0], matrix[N - 1][N -1]
def less_than(mid):
count = 0
row, col = N - 1, 0
while row >= 0 and col < N:
if matrix[row][col] <= mid:
count += row + 1
col += 1
else:
row -= 1
return count
while left <= right:
mid = left + (right - left) //2
if (less_than(mid) < k): left = mid + 1
else: right = mid - 1
return left
时间复杂度: O(nlog(r-l))
空间复杂度: O(1)
思路 先构建一大顶堆,然后取出k小元素 代码(C++)
实现语言: C++
class Solution {
public:
int kthSmallest(vector<vector<int>>& M, int k) {
priority_queue<int, vector<int>, greater<int>> q;
int res;
const int rows = M.size();
const int cols = M.front().size();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
q.push(M[i][j]);
}
}
while (!q.empty() && k - 1 > 0)
{
q.pop();
k--;
}
res = q.empty() ? -1 : q.top();
return res;
}
};
复杂度分析 时间复杂度: O(NlogN) 空间复杂度: O(N)
378. 有序矩阵中第 K 小的元素
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix/
前置知识
题目描述
示例:
matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8,
返回 13。
提示: 你可以假设 k 的值永远是有效的,1 ≤ k ≤ n2 。