link
https://leetcode-cn.com/problems/flipping-an-image/
time consuming
Problem solving: 29 min
Problem solving: 4 min
Title
Given a binary matrix A, we want to flip the image horizontally first, then invert the image and return the result.
To flip a picture horizontally is to flip each line of the picture, that is, reverse the order. For example, the result of horizontally flipping [1, 1, 0] is [0, 1, 1].
Inverting the picture means that all 0s in the picture are replaced by 1s, and all 1s are replaced by 0s. For example, the result of reversing [0, 1, 1] is [1, 0, 0].
prompt:
- 1 <= A.length = A[0].length <= 20
- 0 <= A[i][j] <= 1
Ideas
The simulated question is enough, see the code for details.
Time complexity: O (n 2) O(n^2)O ( n2)
AC code
class Solution {
public:
vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
int n = A.size();
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n/2; ++j) {
swap(A[i][j], A[i][n-j-1]);
}
for(int j = 0; j < n; ++j) {
A[i][j] = (!A[i][j]);
}
}
return A;
}
};