일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- Substring with Concatenation of All Words
- iterator
- 파이썬
- 프로그래머스
- Protocol
- Convert Sorted List to Binary Search Tree
- attribute
- Python Implementation
- Decorator
- 시바견
- 컴퓨터의 구조
- kaggle
- LeetCode
- 30. Substring with Concatenation of All Words
- DWG
- Class
- shiba
- Python
- 운영체제
- concurrency
- data science
- 밴픽
- Regular Expression
- t1
- Generator
- 43. Multiply Strings
- 109. Convert Sorted List to Binary Search Tree
- 315. Count of Smaller Numbers After Self
- Python Code
- 715. Range Module
Archives
- Today
- Total
Scribbling
LeetCode: 378. Kth Smallest Element in a Sorted Matrix 본문
Computer Science/Coding Test
LeetCode: 378. Kth Smallest Element in a Sorted Matrix
focalpoint 2022. 1. 14. 12:42Coming up with O(1) memory solution was very difficult for me.
I refered to this post's last solution.
One thing you should remember about sorted matrix(both for rows and columns) is that it has a very efficient algorithm to find an element or to count the number of elements smaller/bigger than a target within O(N+M) time complexity and O(1) memory complexity.
This problem also lies down on the above algorithm.
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
m = len(matrix)
def count(mid):
cnt = 0
y, x = 0, m - 1
while y <= m - 1 and x >= 0:
if matrix[y][x] <= mid:
cnt += x + 1
y += 1
else:
x -= 1
return cnt
left, right = matrix[0][0], matrix[m-1][m-1]
ret = matrix[m-1][m-1]
while left <= right:
mid = (left + right) // 2
cnt = count(mid)
if cnt < k:
left = mid + 1
else:
ret = min(ret, mid)
right = mid - 1
return ret
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 395. Longest Substring with At Least K Repeating Characters (0) | 2022.01.16 |
---|---|
LeetCode: 384. Shuffle an Array (0) | 2022.01.15 |
LeetCode: 341. Flatten Nested List Iterator (0) | 2022.01.13 |
LeetCode: 334. Increasing Triplet Subsequence (0) | 2022.01.11 |
LeetCode: 329. Longest Increasing Path in a Matrix (0) | 2022.01.11 |