方法1:暴力破解
class Solution:
def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
return sorted([i for i in range(len(mat))], key=lambda x:sum(mat[x]))[:k]
方法2:二分查找+排序
class Solution:
def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
m, n = len(mat), len(mat[0])
stack = []
for i in range(m):
low = 0
high = n-1
while low < high-1:
mid = low+(high-low)//2
if mat[i][mid]:
low = mid
else:
high = mid
if mat[i][high]:
length = high+1
elif mat[i][low]:
length = low+1
else:
length = 0
stack.append([length, i])
stack.sort()
return [an[1] for an in stack[:k]]