add: 有序矩阵中第K小的元素

This commit is contained in:
yi-ge 2020-07-02 11:36:45 +08:00
parent 16ec46e003
commit 89d8ac5e58
3 changed files with 33 additions and 0 deletions

View File

@ -381,6 +381,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 718. 最长重复子数组 <https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray/>
- LintCode 79. 最长公共子串 <https://www.lintcode.com/problem/longest-common-substring/description>
- [有序矩阵中第K小的元素](src/array/kth-smallest-element-in-a-sorted-matrix.js)
- LeetCode 378. 有序矩阵中第K小的元素 <https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix/>
- LintCode 401. 排序矩阵中的从小到大第k个数 <https://www.lintcode.com/problem/kth-smallest-number-in-sorted-matrix/description>
## 栈
- [最大矩阵](src/stack/maximal-rectangle.js)

View File

@ -0,0 +1,8 @@
/**
* @param {number[][]} matrix
* @param {number} k
* @return {number}
*/
export const kthSmallest = function (matrix, k) {
return matrix.flat().sort((a, b) => a - b)[k - 1]
}

View File

@ -0,0 +1,20 @@
import { kthSmallest } from '../../src/array/kth-smallest-element-in-a-sorted-matrix.js'
test('有序矩阵中第K小的元素', () => {
expect(kthSmallest([
[1, 5, 9],
[10, 11, 13],
[12, 13, 15]
], 8)).toBe(13)
expect(kthSmallest([
[1, 5, 7],
[3, 7, 8],
[4, 8, 9]
], 4)).toBe(5)
expect(kthSmallest([
[1, 2],
[3, 4]
], 3)).toBe(3)
})