832. Flipping an Image
Given a binary matrix A
, we want to flip the image horizontally, then invert it, and return the resulting image.
To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0]
horizontally results in [0, 1, 1]
.
To invert an image means that each 0
is replaced by 1
, and each 1
is replaced by 0
. For example, inverting [0, 1, 1]
results in [1, 0, 0]
.
Example 1:
1 | Input: [[1,1,0],[1,0,1],[0,0,0]] |
Example 2:
1 | Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] |
Notes:
1 <= A.length = A[0].length <= 20
0 <= A[i][j] <= 1
题目大概解释一下:二维数组,水平翻转,再取反。
方案一
思路:遍历每一行,对每行的元素先做翻转,再取反,时间复杂度
1 | class Solution { |
result
Runtime: 20 ms, faster than 21.52% of C++ online submissions for Flipping an Image.
Memory Usage: 9.3 MB, less than 100.00% of C++ online submissions for Flipping an Image.
预料到时间会比较高,毕竟时间复杂度是 (后面解释,慢竟然不是因为这个原因)。
方案二
从讨论区里面找到一个方案,再稍微修改下,使用了reverse函数,并通过引用修改原有元素,而且使用了异或操作。
1 | class Solution { |
result
Runtime: 12 ms, faster than 100.00% of C++ online submissions for Flipping an Image.
Memory Usage: 9.3 MB, less than 99.61% of C++ online submissions for Flipping an Image.
其实套路基本差不多,但是有个很关键的操作 i ^= 1;,这个异或操作比方案一的 ! 操作,效率高很多。
把方案一的 ! 操作,换成异或后,也得到了类似的效果,不过新开辟的vector就多了空间复杂度。
Runtime: 12 ms, faster than 100.00% of C++ online submissions for Flipping an Image.
Memory Usage: 9.5 MB, less than 99.22% of C++ online submissions for Flipping an Image.