The title

You are given a matrix mat of size m by n, consisting of a number of soldiers and civilians, represented by ones and zeros.

Return the index of the weakest row k in the matrix, sorted from weakest to strongest.

If line I has fewer soldiers than line J, or if both lines have the same number of soldiers but I is less than J, then line I is considered weaker than line J.

Soldiers are always at the top of the line, which means that the 1 always comes before the 0.

Example 1: input: mat = [,1,0,0,0 [1],,1,1,1,0 [1], [1,0,0,0,0],,1,0,0,0 [1], [1,1,1,1,1]], k = 3 output:,0,3 [2] : soldiers number in each row: Row 0 -> 2 Row 1 -> 4 Row 2 -> 1 row 3 -> 2 row 4 -> 5 Sort these rows from weakest to strongest to get [2,0,3,1,4] Example 2: Input: ,0,0,0 mat = [[1], [1,1,1,1],,0,0,0 [1], [1,0,0,0]], k = 2 output: [0, 2] explanation: the number of soldiers in the line: Row 0 -> 1 row 1 -> 4 row 2 -> 1 row 3 -> 1 Sort these rows from weakest to strongest to get [0,2,3,1]Copy the code

Tip:

M == mat.length n == mat.length 2 <= n, m <= 100 1 <= k <= m matrix[I][j

Their thinking

class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: Count (1) = count (1) CountList = [[index, val.count(1)] for index,val in enumerate(mat)] # for index,val in enumerate(mat): # print(index,val) countList.sort(key=lambda x: (x[1], x[0])) resList = [i[0] for i in countList] return resList[:k] if __name__ == '__main__': mat = [[1, 1, 0, 0, 0], [1, 1, 1, 1, 0], [1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 1, 1, 1, 1]] k = 3 ret = Solution().kWeakestRows(mat, k) print(ret)Copy the code