|
| 1 | +# 0378. Kth Smallest Element in a Sorted Matrix |
| 2 | + |
| 3 | +* Difficulty: medium |
| 4 | +* Link: https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/ |
| 5 | +* Topics: Binary-Search, Heap |
| 6 | + |
| 7 | +# Clarification |
| 8 | + |
| 9 | +1. Check the inputs and outputs |
| 10 | + - INPUT: matrix[int][int] |
| 11 | + - OUTPUT: int |
| 12 | +2. Check the main goal |
| 13 | + - time complexity < $O(n^2)$ |
| 14 | + |
| 15 | +# Naive Solution |
| 16 | + |
| 17 | +<aside> |
| 18 | +💡 從最簡單的方法開始 easy solution → only speak out |
| 19 | + |
| 20 | +</aside> |
| 21 | + |
| 22 | +### Thought Process |
| 23 | + |
| 24 | +1. 遍歷整個矩陣,找出第 k 小的值 ⇒ $O(n^2)$ 不符合題目要求 |
| 25 | + |
| 26 | +# Solution (Binary search) |
| 27 | + |
| 28 | +### Thought Process |
| 29 | + |
| 30 | +1. 定義 (依據 matrix 之特性) |
| 31 | + - lower = matrix[0][0] |
| 32 | + - upper = matrxi[n][n] |
| 33 | +- 猜中間值,並算出有多少個數小於該個中間值 |
| 34 | + - 個數 < target ⇒ lower = mid + 1 |
| 35 | + - 個數 ≥ target ⇒ upper = mid |
| 36 | +- 當 lower ≥ upper 時跳出迴圈,並回傳 lower(/upper)都行 |
| 37 | +- Implement |
| 38 | + |
| 39 | + ```python |
| 40 | + class Solution: |
| 41 | + def kthSmallest(self, matrix: List[List[int]], k: int) -> int: |
| 42 | + lower = matrix[0][0] |
| 43 | + upper = matrix[-1][-1] |
| 44 | + while lower < upper: |
| 45 | + mid = (lower+upper) // 2 |
| 46 | + count = self.numberOfElementsLessOrEqualThan(matrix, mid) |
| 47 | + if count < k: |
| 48 | + lower = mid + 1 |
| 49 | + else: |
| 50 | + upper = mid |
| 51 | + return lower |
| 52 | + |
| 53 | + def numberOfElementsLessOrEqualThan(self, matrix: List[List[int]], target: int) -> int: |
| 54 | + l = len(matrix) |
| 55 | + i = 0 |
| 56 | + j = l - 1 |
| 57 | + count = 0 |
| 58 | + while j >= 0 and i < l: |
| 59 | + if target < matrix[i][j]: |
| 60 | + j -= 1 |
| 61 | + if target >= matrix[i][j]: |
| 62 | + count += (j+1) |
| 63 | + i += 1 |
| 64 | + return count |
| 65 | + ``` |
| 66 | + |
| 67 | + |
| 68 | +### Complexity |
| 69 | + |
| 70 | +- Time complexity: O(log n) |
| 71 | +- Space complexity: O(1) |
| 72 | + |
| 73 | +# Solution (Heap) |
| 74 | + |
| 75 | +- tbd |
| 76 | + |
| 77 | +# Note |
| 78 | + |
| 79 | +- ****[K-th Smallest Element in a Sorted Matrix](https://www.tutorialcup.com/interview/matrix/k-th-smallest-element-in-a-sorted-matrix.htm#Using_min_Heap_data_structure)**** |
| 80 | +- ****[LeetCode 378(Find K Pairs with Smallest Sums) 心得(Medium)](https://medium.com/@ChYuan/leetcode-378-find-k-pairs-with-smallest-sums-%E5%BF%83%E5%BE%97-medium-c2430d02f260)**** |
0 commit comments