LeetCode 题解工作台
翻转矩阵后的得分
给你一个大小为 m x n 的二元矩阵 grid ,矩阵中每个元素的值为 0 或 1 。 一次 移动 是指选择任一行或列,并转换该行或列中的每一个值:将所有 0 都更改为 1 ,将所有 1 都更改为 0 。 在做出任意次数的移动后,将该矩阵的每一行都按照二进制数来解释,矩阵的 得分 就是这些数字的总…
4
题型
6
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
我们注意到,对于任意一个翻转方案,翻转的次序不影响最后的结果。因此我们可以先考虑所有的行翻转,再考虑所有的列翻转。 每一行的数字要尽可能大,因此,我们遍历每一行,若行首元素为 ,则将该行进行翻转。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个大小为 m x n 的二元矩阵 grid ,矩阵中每个元素的值为 0 或 1 。
一次 移动 是指选择任一行或列,并转换该行或列中的每一个值:将所有 0 都更改为 1,将所有 1 都更改为 0。
在做出任意次数的移动后,将该矩阵的每一行都按照二进制数来解释,矩阵的 得分 就是这些数字的总和。
在执行任意次 移动 后(含 0 次),返回可能的最高分数。
示例 1:
输入:grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]] 输出:39 解释:0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39
示例 2:
输入:grid = [[0]] 输出:1
提示:
m == grid.lengthn == grid[i].length1 <= m, n <= 20grid[i][j]为0或1
解题思路
方法一:贪心
我们注意到,对于任意一个翻转方案,翻转的次序不影响最后的结果。因此我们可以先考虑所有的行翻转,再考虑所有的列翻转。
每一行的数字要尽可能大,因此,我们遍历每一行,若行首元素为 ,则将该行进行翻转。
接下来,对于每一列 ,我们统计该列中 和 的数量,令 为其中的最大值,则该列的贡献为 。对所有列的贡献进行累加,即可得到答案。
时间复杂度 ,空间复杂度 。其中 , 分别为矩阵的行数和列数。
class Solution:
def matrixScore(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
for i in range(m):
if grid[i][0] == 0:
for j in range(n):
grid[i][j] ^= 1
ans = 0
for j in range(n):
cnt = sum(grid[i][j] for i in range(m))
ans += max(cnt, m - cnt) * (1 << (n - j - 1))
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(m \cdot n) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Look for an approach that efficiently handles the greedy choice of flipping rows and columns.
- question_mark
Ensure the candidate can correctly apply invariant validation to the matrix after row flips.
- question_mark
The candidate should demonstrate the ability to compute the final score efficiently.
常见陷阱
外企场景- error
Failing to flip rows initially to ensure the most significant bit is 1.
- error
Not correctly validating column flips based on the number of 1's and 0's.
- error
Overcomplicating the solution by not sticking to the greedy choice plus invariant validation pattern.
进阶变体
外企场景- arrow_right_alt
Consider the scenario where m or n is at the upper limit of 20, testing the scalability of the approach.
- arrow_right_alt
Modify the problem to allow flipping only rows or only columns, testing how the solution adapts to different constraints.
- arrow_right_alt
Introduce additional constraints on which rows and columns can be flipped based on certain conditions, adding complexity to the problem.