LeetCode 题解工作台

矩阵中战斗力最弱的 K 行

给你一个大小为 m * n 的矩阵 mat ,矩阵由若干军人和平民组成,分别用 1 和 0 表示。 请你返回矩阵中战斗力最弱的 k 行的索引,按从最弱到最强排序。 如果第 i 行的军人数量少于第 j 行,或者两行军人数量相同但 i 小于 j ,那么我们认为第 i 行的战斗力比第 j 行弱。 军人 总…

category

5

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 二分·搜索·答案·空间

bolt

答案摘要

class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个大小为 m * n 的矩阵 mat,矩阵由若干军人和平民组成,分别用 1 和 0 表示。

请你返回矩阵中战斗力最弱的 k 行的索引,按从最弱到最强排序。

如果第 i 行的军人数量少于第 j 行,或者两行军人数量相同但 i 小于 j,那么我们认为第 i 行的战斗力比第 j 行弱。

军人 总是 排在一行中的靠前位置,也就是说 1 总是出现在 0 之前。

 

示例 1:

输入: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
输出:[2,0,3]
解释:
每行中的军人数目:
行 0 -> 2 
行 1 -> 4 
行 2 -> 1 
行 3 -> 2 
行 4 -> 5 
从最弱到最强对这些行排序后得到 [2,0,3,1,4]

示例 2:

输入:mat = 
[[1,0,0,0],
 [1,1,1,1],
 [1,0,0,0],
 [1,0,0,0]], 
k = 2
输出:[0,2]
解释: 
每行中的军人数目:
行 0 -> 1 
行 1 -> 4 
行 2 -> 1 
行 3 -> 1 
从最弱到最强对这些行排序后得到 [0,2,3,1]

 

提示:

  • m == mat.length
  • n == mat[i].length
  • 2 <= n, m <= 100
  • 1 <= k <= m
  • matrix[i][j] 不是 0 就是 1
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
class Solution:
    def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
        m, n = len(mat), len(mat[0])
        ans = [n - bisect_right(row[::-1], 0) for row in mat]
        idx = list(range(m))
        idx.sort(key=lambda i: ans[i])
        return idx[:k]
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Check if the candidate efficiently applies binary search to count soldiers in each row.

  • question_mark

    Evaluate how the candidate handles sorting and tie-breaking when soldier counts are equal.

  • question_mark

    Assess the candidate's ability to optimize for both time and space complexity within the problem's constraints.

warning

常见陷阱

外企场景
  • error

    Misunderstanding the requirement for sorting rows based on both soldier count and row index in case of ties.

  • error

    Using a brute-force approach to count soldiers in each row instead of binary search, leading to inefficiency.

  • error

    Not properly handling edge cases, such as when multiple rows have the same number of soldiers.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Handling larger matrices where time and space complexity become more significant.

  • arrow_right_alt

    Modifying the problem to return the indices of the k strongest rows instead of the weakest.

  • arrow_right_alt

    Allowing for different sorting criteria, such as sorting by the number of civilians instead of soldiers.

help

常见问题

外企场景

矩阵中战斗力最弱的 K 行题解:二分·搜索·答案·空间 | LeetCode #1337 简单