LeetCode 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
2
3
4
Input: [[1,1,0],[1,0,1],[0,0,0]]
Output: [[1,0,0],[0,1,0],[1,1,1]]
Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].
Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]

Example 2:

1
2
3
4
Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].
Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]

Note:

1
2
1 <= A.length = A[0].length <= 20
0 <= A[i][j] <= 1

题目大意:

根据给出的例子可以发现规则:
翻转图像矩阵的每一行,并且对每一个元素取反

解题思路:


这道题总共要做2件事:

1. 数组中的每个单元逆序
2. 数组中的每个单元内的元素求反

参考LeetCode Discuss:
https://leetcode.com/problems/flipping-an-image/discuss/130590/C++JavaPython-Reverse-and-Toggle

C++代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
vector<vector<int> > vRes = A;
if (0 == vRes.size()) return vRes;
for (int idx = 0; idx < vRes.size(); idx++) {
vector<int>& v = vRes[idx];
reverse(v.begin(), v.end());
vector<int>::iterator it = v.begin();
for (; it != v.end(); it++) {
*it = *it ^ 1;
}
}
return vRes;
}
};

代码分析:
此题元素求反可以考虑(数组内的元素非0即1):

1. 元素本身异或
2. 元素本身求反
3. 代码本身判断
------本文结束感谢阅读------
坚持原创技术分享,您的支持将鼓励我继续创作!
显示 Gitment 评论