LeetCode 题解工作台
判断矩阵是否是一个 X 矩阵
如果一个正方形矩阵满足下述 全部 条件,则称之为一个 X 矩阵 : 矩阵对角线上的所有元素都 不是 0 矩阵中所有其他元素都是 0 给你一个大小为 n x n 的二维整数数组 grid ,表示一个正方形矩阵。如果 grid 是一个 X 矩阵 ,返回 true ;否则,返回 false 。 示例 1:…
2
题型
8
代码语言
3
相关题
当前训练重点
简单 · 数组·matrix
答案摘要
我们可以直接遍历矩阵,对于每个元素,判断其是否满足 矩阵的条件。若不满足,直接返回 ;若遍历完所有元素都满足,返回 。 时间复杂度 ,其中 为矩阵的行数或列数。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·matrix 题型思路
题目描述
如果一个正方形矩阵满足下述 全部 条件,则称之为一个 X 矩阵 :
- 矩阵对角线上的所有元素都 不是 0
- 矩阵中所有其他元素都是 0
给你一个大小为 n x n 的二维整数数组 grid ,表示一个正方形矩阵。如果 grid 是一个 X 矩阵 ,返回 true ;否则,返回 false 。
示例 1:
输入:grid = [[2,0,0,1],[0,3,1,0],[0,5,2,0],[4,0,0,2]] 输出:true 解释:矩阵如上图所示。 X 矩阵应该满足:绿色元素(对角线上)都不是 0 ,红色元素都是 0 。 因此,grid 是一个 X 矩阵。
示例 2:
输入:grid = [[5,7,0],[0,3,1],[0,5,0]] 输出:false 解释:矩阵如上图所示。 X 矩阵应该满足:绿色元素(对角线上)都不是 0 ,红色元素都是 0 。 因此,grid 不是一个 X 矩阵。
提示:
n == grid.length == grid[i].length3 <= n <= 1000 <= grid[i][j] <= 105
解题思路
方法一:模拟
我们可以直接遍历矩阵,对于每个元素,判断其是否满足 矩阵的条件。若不满足,直接返回 ;若遍历完所有元素都满足,返回 。
时间复杂度 ,其中 为矩阵的行数或列数。空间复杂度 。
class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
for i, row in enumerate(grid):
for j, v in enumerate(row):
if i == j or i + j == len(grid) - 1:
if v == 0:
return False
elif v:
return False
return True
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate demonstrates understanding of matrix traversal and diagonal checking.
- question_mark
Look for an efficient solution that iterates through the matrix once, checking both conditions.
- question_mark
Candidate should handle edge cases, such as matrices where all elements are zero or matrices that are clearly non-X-Matrices.
常见陷阱
外企场景- error
Misunderstanding the diagonal pattern or incorrectly checking non-diagonal elements.
- error
Over-complicating the solution by requiring additional space when O(1) space is sufficient.
- error
Not accounting for all matrix elements in the check, leading to incorrect results.
进阶变体
外企场景- arrow_right_alt
Adjust the problem to consider non-square matrices or non-integer elements.
- arrow_right_alt
Implement additional constraints like handling large grids efficiently.
- arrow_right_alt
Consider edge cases where the matrix has the minimum size (3x3) or elements are at their maximum values.