LeetCode 题解工作台
翻转图像
给定一个 n x n 的二进制矩阵 image ,先 水平 翻转图像,然后 反转 图像并返回 结果 。 水平 翻转图片就是将图片的每一行都进行翻转,即逆序。 例如,水平翻转 [1,1,0] 的结果是 [0,1,1] 。 反转 图片的意思是图片中的 0 全部被 1 替换, 1 全部被 0 替换。 例如…
5
题型
5
代码语言
3
相关题
当前训练重点
简单 · 双·指针·invariant
答案摘要
我们可以遍历矩阵,对于遍历到的每一行 ,我们使用双指针 和 分别指向该行的首尾元素,如果 $\textit{row}[i] = \textit{row}[j]$,交换后两者的值仍然保持不变,因此,我们只需要对 和 进行异或反转即可,然后将 和 分别向中间移动一位,直到 $i \geq j$。如果 $\textit{row}[i] \neq \textit{row}[j]$,此时交换后再…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给定一个 n x n 的二进制矩阵 image ,先 水平 翻转图像,然后 反转 图像并返回 结果 。
水平翻转图片就是将图片的每一行都进行翻转,即逆序。
- 例如,水平翻转
[1,1,0]的结果是[0,1,1]。
反转图片的意思是图片中的 0 全部被 1 替换, 1 全部被 0 替换。
- 例如,反转
[0,1,1]的结果是[1,0,0]。
示例 1:
输入:image = [[1,1,0],[1,0,1],[0,0,0]]
输出:[[1,0,0],[0,1,0],[1,1,1]]
解释:首先翻转每一行: [[0,1,1],[1,0,1],[0,0,0]];
然后反转图片: [[1,0,0],[0,1,0],[1,1,1]]
示例 2:
输入:image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
输出:[[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
解释:首先翻转每一行: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]];
然后反转图片: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
提示:
n == image.lengthn == image[i].length1 <= n <= 20images[i][j]==0或1.
解题思路
方法一:双指针
我们可以遍历矩阵,对于遍历到的每一行 ,我们使用双指针 和 分别指向该行的首尾元素,如果 ,交换后两者的值仍然保持不变,因此,我们只需要对 和 进行异或反转即可,然后将 和 分别向中间移动一位,直到 。如果 ,此时交换后再反转两者的值,仍然保持不变,因此,可以不进行任何操作。
最后,如果 ,我们直接对 进行反转即可。
时间复杂度 ,其中 是矩阵的行数或列数。空间复杂度 。
class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
n = len(image)
for row in image:
i, j = 0, n - 1
while i < j:
if row[i] == row[j]:
row[i] ^= 1
row[j] ^= 1
i, j = i + 1, j - 1
if i == j:
row[i] ^= 1
return image
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(N^2) because each of the N rows of length N is scanned once. Space complexity is O(1) since all operations are performed in place with no extra storage. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Check if the candidate correctly flips rows without using extra arrays.
- question_mark
Watch whether inversion is combined with swapping or done in a separate pass.
- question_mark
Confirm that middle elements in odd-length rows are handled without errors.
常见陷阱
外企场景- error
Swapping values without inverting them at the same time causes incorrect final results.
- error
Off-by-one errors when moving two pointers can skip elements or double-invert.
- error
Failing to handle odd-length rows' middle element separately leads to wrong inversion.
进阶变体
外企场景- arrow_right_alt
Apply the same two-pointer flip and invert approach on a rectangular matrix instead of a square one.
- arrow_right_alt
Perform horizontal flip only, without inversion, to isolate the flipping logic.
- arrow_right_alt
Invert all elements without flipping to practice bit manipulation in place.