티스토리 뷰
Leetocode 378 Kth Smallest Element in a Sorted Matrix
juniz 2020. 6. 22. 23:22Question
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
return 13.
처음 생각한 간단한 방식은
matrix를 flatten 한 뒤 그 리스트의 k-1번째 인덱스를 리턴하면 될 듯하여 만든 코드입니다.
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
import operator
temp = reduce(operator.concat, matrix)
return sorted(temp)[k-1]
numpy.flatten() 대신에 사용할만한 것을 찾다 보니 operator.concat을 사용하면 된다고 해서 사용해 봤습니다.
그 외에 stackoverflow에서 다양한 테스트를 해주신 분 있어서 참고하면 좋을 듯 합니다.
https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists
How to make a flat list out of list of lists?
I wonder whether there is a shortcut to make a simple list out of list of lists in Python. I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with reduce(), but I ge...
stackoverflow.com
.reduce()
def int_sum(x1, x2):
return x1 + x2
from functools import reduce
reduce(int_sum, [1,2,3,4])
# 10
'Development > Algorithms' 카테고리의 다른 글
Reverse string with python3 (0) | 2020.07.29 |
---|---|
Valid Palindrome in python3 (0) | 2020.07.29 |
Leetcode No. 234 && 206 Linked List basic Problem (1) | 2020.06.09 |
Leetcode 35 Search insert Position (2) | 2020.06.08 |
Leetcode 67. Add Binary (2) | 2020.06.07 |
- Total
- Today
- Yesterday
- leetcode
- 나는리뷰어다
- book
- Container
- go
- 책리뷰
- K8S
- palindrome
- csv
- LLM
- Fine-Tuning
- 한빛미디어
- Python
- lllm
- feed-forward
- 키보드
- kubens
- Shell
- error
- docker
- Git
- Binary
- AWS
- BASIC
- collator
- Algorithm
- Kubernetes
- Gemma
- kubernetes context
- 파이썬
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |