标签:font object ret 矩阵 int pytho loading solution else
方法一:二分查找。
class Solution(object):
# 二分查找
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
n = len(matrix)
low, high = matrix[0][0], matrix[n - 1][n - 1]
while low < high:
# 计算矩阵中值
mid = low + int((high - low) / 2)
# 统计小于等于mid的元素个数
count = 0
i, j = 0, n - 1
while j >= 0 and i < n:
if matrix[i][j] <= mid:
count += j + 1
i += 1
else:
j -= 1
if count < k:
low = mid + 1
else:
high = mid
return low
方法二:暴力解。
class Solution(object):
# 代码一
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
temp = []
for i in range(len(matrix)):
temp += matrix[i]
temp.sort()
return temp[k - 1]
# 代码二
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
m = len(matrix)
n = len(matrix[0])
temp = matrix[0]
for i in range(1, m):
for j in range(n):
temp.append(matrix[i][j])
temp.sort()
return temp[k - 1]
标签:font object ret 矩阵 int pytho loading solution else
原文地址:https://www.cnblogs.com/panweiwei/p/13065237.html