题目:给定一个二进制矩阵 A,我们想先水平翻转图像,然后反转图像并返回结果。水平翻转图片就是将图片的每一行都进行翻转,即逆序。
例如,水平翻转 [1, 1, 0] 的结果是 [0, 1, 1]。反转图片的意思是图片中的 0 全部被 1 替换, 1 全部被 0 替换。例如,反转 [0, 1, 1] 的结果是 [1, 0, 0]。
示例 1:
输入:[[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:
输入:[[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]]
1.原创
class Solution {
public:
vector<vector<int>> flipAndInvertImage(vector<vector<int>>& image) {
vector<vector<int>> res;
for (auto sub_list:image){
reverse(sub_list.begin(),sub_list.end());
vector<int> temp;
for (int i=0; i<sub_list.size();++i){
if (sub_list[i]==0)
temp.push_back(1);
else
temp.push_back(0);
}
res.push_back(temp);
}
return res;
}
};
2.题解
class Solution {
public:
vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
int m = A.size(), n = A[0].size();
for (int i = 0; i < m; i++) {
for (int j = 0, k = n - 1; j <= k; j++, k--) {
int a = !A[i][j], b = !A[i][k];// 或者 int a = A[i][j] ^ 1, b = A[i][k] ^ 1;
A[i][j] = b, A[i][k] = a;
}
}
return A;
}
};
作者:yexiso
链接:https://leetcode-cn.com/problems/flipping-an-image/solution/cjie-fa-fan-zhuan-fan-zhuan-by-yexiso-cyue/