Loading...

09-18 leetcode-1337

链接 1337. The K Weakest Rows in a Matrix

题目

You are given an m x n binary matrix mat of 1’s (representing soldiers) and 0’s (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1’s will appear to the left of all the 0’s in each row.

A row i is weaker than a row j if one of the following is true:

The number of soldiers in row i is less than the number of soldiers in row j.
Both rows have the same number of soldiers and i < j.
Return the indices of the k weakest rows in the matrix ordered from weakest to strongest.

题解

这题直接用堆暴力写了

1
2
3
4
5
6
7
8
9
import heapq


class Solution:
def kWeakestRows(self, mat: list[list[int]], k: int) -> list[int]:
heap = []
for index, value in enumerate(mat):
heapq.heappush(heap, (value.count(1), index))
return [heapq.heappop(heap)[1] for _ in range(k)]

Comment