파비의 매일매일 공부기록

Today's Challenge 본문

Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 8. 2. 23:45

https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/

 

Kth Smallest Element in a Sorted Matrix - LeetCode

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

단순히 배열을 합쳐서 정렬하면 끝나는 문제이긴 한데,
n이 커지면 이런 방법으로는 불가함. 그래서 binary search를 이용하면 됨.

class Solution:
    def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
        l, r, n = matrix[0][0], matrix[-1][-1], len(matrix)
        
        def less_k(m):
            cnt = 0
            for r in range(n):
                x = bisect_right(matrix[r], m)
                cnt += x
            return cnt
    
        while l < r:
            mid = (l + r) // 2
            
            if less_k(mid) < k:
                l = mid + 1
            else:
                r = mid
        
        return l
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

Today's Challenge  (0) 2022.08.04
Today's Challenge  (0) 2022.08.03
Today's Challenge  (0) 2022.08.01
Today's Challenge  (0) 2022.07.31
Today's Challenge  (0) 2022.07.30
Comments