LeetCode 题解工作台
统计有序矩阵中的负数
给你一个 m * n 的矩阵 grid ,矩阵中的元素无论是按行还是按列,都以非严格递减顺序排列。 请你统计并返回 grid 中 负数 的数目。 示例 1: 输入: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] 输出: 8 解释: …
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 二分·搜索·答案·空间
答案摘要
由于矩阵是按行和按列非严格递减排序的,我们可以从矩阵的左下角开始遍历,记当前位置为 $(i, j)$。 如果当前位置的元素大于等于 ,说明该行的前面所有元素也都大于等于 ,因此我们将列索引 向右移动一位,即 $j = j + 1$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给你一个 m * n 的矩阵 grid,矩阵中的元素无论是按行还是按列,都以非严格递减顺序排列。 请你统计并返回 grid 中 负数 的数目。
示例 1:
输入:grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] 输出:8 解释:矩阵中共有 8 个负数。
示例 2:
输入:grid = [[3,2],[1,0]] 输出:0
提示:
m == grid.lengthn == grid[i].length1 <= m, n <= 100-100 <= grid[i][j] <= 100
进阶:你可以设计一个时间复杂度为 O(n + m) 的解决方案吗?
解题思路
方法一:从左下角开始遍历
由于矩阵是按行和按列非严格递减排序的,我们可以从矩阵的左下角开始遍历,记当前位置为 。
如果当前位置的元素大于等于 ,说明该行的前面所有元素也都大于等于 ,因此我们将列索引 向右移动一位,即 。
如果当前位置的元素小于 ,说明该列的当前元素以及其右侧的所有元素都是负数,因此我们可以将负数的数量增加 (其中 是矩阵的列数),然后将行索引 向上移动一位,即 。
我们重复上述过程,直到行索引 小于 或列索引 大于等于 。最终,负数的数量即为答案。
时间复杂度 ,其中 和 分别是矩阵的行数和列数。空间复杂度 。
class Solution:
def countNegatives(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
i, j = m - 1, 0
ans = 0
while i >= 0 and j < n:
if grid[i][j] >= 0:
j += 1
else:
ans += n - j
i -= 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate may demonstrate an understanding of binary search optimization.
- question_mark
Look for efficient handling of the matrix’s sorted properties.
- question_mark
Candidates should be able to quickly decide between brute force and optimized approaches.
常见陷阱
外企场景- error
Failing to recognize that binary search can be used due to the sorted matrix.
- error
Inadequate handling of early exits when searching through rows.
- error
Over-complicating the solution by not leveraging matrix properties effectively.
进阶变体
外企场景- arrow_right_alt
The problem can be varied by changing the matrix dimensions or having different constraints on the range of values.
- arrow_right_alt
You can modify the matrix to be sorted in a different order (non-increasing vs non-decreasing) and require adaptation of the approach.
- arrow_right_alt
The problem can be extended to handle larger matrices with additional memory and performance considerations.