每日Leecode算法题:1337.矩阵中战斗力最弱的k行

每日Leecode算法题:1337.矩阵中战斗力最弱的k行_第1张图片

 方法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]]

你可能感兴趣的:(Leecode算法题专栏,算法,python,数据结构,排序算法)