1337. The K Weakest Rows in a Matrix

Given a m * n matrix mat of ones (representing soldiers) and zeros (representing civilians), return the indexes of the k weakest rows in the matrix ordered from the weakest to the strongest.

A row i is weaker than row j, if the number of soldiers in row i is less than the number of soldiers in row j, or they have the same number of soldiers but i is less than j. Soldiers are always stand in the frontier of a row, that is, always ones may appear first and then zeros.

对每行二分搜索统计1的个数,然后['index': index, 'count': count] 按照count排序,拿到前k个的index就是答案

class Solution(object):
    def kWeakestRows(self, mat, k):
        """
        :type mat: List[List[int]]
        :type k: int
        :rtype: List[int]
        """
        count = []
        for row in mat:
            l = 0
            r = len(row) - 1
            while l <= r:
                mid = (l + r) // 2
                if row[mid] == 1:
                    l = mid + 1
                else:
                    r = mid - 1
            count.append({"index": len(count), "count": l})
        count = sorted(count, key=lambda x: x["count"])
        ans = []
        for i in range(0, k, 1):
            ans.append(count[i]["index"])
        return ans
            
原文地址:https://www.cnblogs.com/whatyouthink/p/13208003.html