1,题目要求
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].
给出一个01矩阵,将其翻转再取反(0-1,1-0)。
2,题目思路
题目看起来有点复杂,其实是要分别对每一行进行单独的处理即可。翻转只是前后数字的交换,取反只是0-1的变换,总体而言并不难。
参考了discussion之后,有一种思路一样但是更简单的办法,直接使用STL的特性来实现,代码更为的简洁,只是效率上并没有太多的提高。
3,程序源码
1:
class Solution {
public:
vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
int row = A.size();
if(row == 0) return A;
int col = A[0].size();
for(int i=0;i<row;i++)
flip_reverse(A[i],col);
return A;
}
private:
void flip_reverse(vector<int>& v, int len)
{
for(int i = 0;i<len/2;i++)
swap(v[i], v[len-i-1]);
for(int i = 0;i<len;i++)
v[i] = v[i]==1?0:1;
}
};
2:
class Solution {
public:
vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
for (auto & row : A) reverse(row.begin(), row.end());
for (auto & row : A) for (int & i: row) i^=1; //按位异或
return A;
}
};