일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 파이썬
- attribute
- 운영체제
- 43. Multiply Strings
- 715. Range Module
- 30. Substring with Concatenation of All Words
- 밴픽
- iterator
- Python Code
- t1
- 109. Convert Sorted List to Binary Search Tree
- 315. Count of Smaller Numbers After Self
- 프로그래머스
- 시바견
- Python
- Substring with Concatenation of All Words
- Decorator
- Convert Sorted List to Binary Search Tree
- 컴퓨터의 구조
- Regular Expression
- concurrency
- DWG
- Protocol
- data science
- Python Implementation
- kaggle
- Class
- shiba
- Generator
- LeetCode
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.
[C++/Java/Python] MaxHeap, MinHeap, Binary Search - Picture Explain - Clean & Concise - LeetCode Discuss
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
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 |