# LeetCode 378

    def kthSmallest2(self, matrix: List[List[int]], k: int) -> int:
N = len(matrix)
h = []
visited = set()
collections._heapq.heappush(h, [matrix[0][0], 0, 0])
while k>0 and h:
cval, posx, posy = collections._heapq.heappop(h)
k = k-1

rightx, righty = posx+1, posy
if rightx < N and righty < N and (rightx, righty) not in visited:
collections._heapq.heappush(h, [matrix[rightx][righty], rightx, righty])

bottomx, bottomy = posx, posy +1
if bottomx < N and bottomy < N and (bottomx, bottomy) not in visited:
collections._heapq.heappush(h, [matrix[bottomx][bottomy], bottomx, bottomy])

return cval


    def kthSmallest1(self, matrix: List[List[int]], k: int) -> int:
N = len(matrix)
h = []
for i in range(0, N):
for j in range(0, N):
collections._heapq.heappush(h, -matrix[i][j])
if len(h) > k:
collections._heapq.heappop(h)

return - collections._heapq.heappop(h)


    def kthSmallest(self, matrix: List[List[int]], k: int) -> int:

# binary search
def helper(thr,matrix,k):
count = 0
for i in range(len(matrix)):
L,R = 0,len(matrix[i])-1
while L<=R:
mid = (L+R)//2
if matrix[i][mid]<thr:
L = mid+1
else:
R = mid-1
count+=L
return count<k

n = len(matrix)
L = ans = matrix[0][0]
R = matrix[n-1][n-1]

while L<=R:
mid = (L+R)//2
if helper(mid,matrix,k):
ans = mid
L = mid+1
else:
R = mid-1
return ans


    def findKthNumber(self, m: int, n: int, k: int) -> int:
left = 1
right = m*n

def count(val, m, n):
c = 0
for i in range(1, m+1):
if i > val: break
c += min(n, val // i)
return c

while left <= right:
mid = left + ((right-left) >> 1)
if count(mid, m, n) >= k:
right = mid -1
else:
left = mid + 1

return left


10-07 852

01-19 204

02-20 13

03-15 1840

07-20 179

02-18 33

10-02 83

02-26 83

04-21 112

08-20 3698

03-24 747

09-14 634

11-17 183

11-30 533

08-02 2869

08-01 3841

09-27 125

08-23 468

07-23 874

09-23 180

#### Leetcode378: Kth Smallest Element in a Sorted Matrix

©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客