LeetCode 题解工作台
查询后矩阵的和
给你一个整数 n 和一个下标从 0 开始的 二维数组 queries ,其中 queries[i] = [type i , index i , val i ] 。 一开始,给你一个下标从 0 开始的 n x n 矩阵,所有元素均为 0 。每一个查询,你需要执行以下操作之一: 如果 type i ==…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
由于每一行、每一列的值取决于最后一次的修改,因此,我们不妨倒序遍历所有的查询,使用哈希表 和 记录有哪些行和列被修改过。 对于每一次查询 $(t, i, v)$:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个整数 n 和一个下标从 0 开始的 二维数组 queries ,其中 queries[i] = [typei, indexi, vali] 。
一开始,给你一个下标从 0 开始的 n x n 矩阵,所有元素均为 0 。每一个查询,你需要执行以下操作之一:
- 如果
typei == 0,将第indexi行的元素全部修改为vali,覆盖任何之前的值。 - 如果
typei == 1,将第indexi列的元素全部修改为vali,覆盖任何之前的值。
请你执行完所有查询以后,返回矩阵中所有整数的和。
示例 1:

输入:n = 3, queries = [[0,0,1],[1,2,2],[0,2,3],[1,0,4]] 输出:23 解释:上图展示了每个查询以后矩阵的值。所有操作执行完以后,矩阵元素之和为 23 。
示例 2:

输入:n = 3, queries = [[0,0,4],[0,1,2],[1,0,1],[0,2,3],[1,2,1]] 输出:17 解释:上图展示了每一个查询操作之后的矩阵。所有操作执行完以后,矩阵元素之和为 17 。
提示:
1 <= n <= 1041 <= queries.length <= 5 * 104queries[i].length == 30 <= typei <= 10 <= indexi < n0 <= vali <= 105
解题思路
方法一:哈希表
由于每一行、每一列的值取决于最后一次的修改,因此,我们不妨倒序遍历所有的查询,使用哈希表 和 记录有哪些行和列被修改过。
对于每一次查询 :
- 如果 ,那么我们判断第 行是否被修改过,如果没有,那么我们将 累加到答案中,其中 表示 的大小,然后将 加入 中;
- 如果 ,那么我们判断第 列是否被修改过,如果没有,那么我们将 累加到答案中,其中 表示 的大小,然后将 加入 中。
最后返回答案。
时间复杂度 ,空间复杂度 。其中 表示查询的次数。
class Solution:
def matrixSumQueries(self, n: int, queries: List[List[int]]) -> int:
row = set()
col = set()
ans = 0
for t, i, v in queries[::-1]:
if t == 0:
if i not in row:
ans += v * (n - len(col))
row.add(i)
else:
if i not in col:
ans += v * (n - len(row))
col.add(i)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(q + n) where q is the number of queries, since each query is checked at most once using hash sets. Space complexity is O(n) for tracking updated rows and columns, avoiding full matrix storage. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ask about efficient handling of large n and query lists using hash sets.
- question_mark
Look for recognition that processing queries in reverse simplifies sum calculation.
- question_mark
Expect candidate to avoid naive O(n^2 * q) approaches due to overwriting updates.
常见陷阱
外企场景- error
Updating the entire matrix for each query leads to timeouts on large inputs.
- error
Ignoring reverse processing may result in double-counting overwritten values.
- error
Forgetting to account for already updated rows or columns causes incorrect sums.
进阶变体
外企场景- arrow_right_alt
Calculate the sum after queries if updates increment rather than overwrite previous values.
- arrow_right_alt
Handle a rectangular m x n matrix instead of a square n x n matrix.
- arrow_right_alt
Return the sum after only a subset of queries, testing partial update tracking.