Title Description
Analysis topics
According to the meaning of the title, we only need to reverse each subarray first, and then replace 0 - > 1 and 1 - > 0, so we can write the following code:
/** * @param {number[][]} A * @return {number[][]} */ var flipAndInvertImage = function(A) { for (let i = 0; i < A.length; i++) { let j = 0, k = A[i].length - 1 while (j < k) { [A[i][j], A[i][k]] = [A[i][k], A[i][j]] A[i][j] = A[i][j] ? 0 : 1 A[i][k] = A[i][k] ? 0 : 1 j++, k-- } if (j === k) { A[i][j] = A[i][j] ? 0 : 1 } } return A };
optimization
For the substitution of 0 - > 1 and 1 - > 0, we can simplify the code as follows, instead of using ternary operators, we can use exclusive or operations.
/** * @param {number[][]} A * @return {number[][]} */ var flipAndInvertImage = function(A) { for (let i = 0; i < A.length; i++) { let j = 0, k = A[i].length - 1 while (j < k) { [A[i][j], A[i][k]] = [A[i][k], A[i][j]] A[i][j] ^= 1 A[i][k] ^= 1 j++, k-- } if (j === k) { A[i][j] ^= 1 } } return A };
Advanced
Looking carefully at the test cases provided in the title, we find that when the left and right numbers are not equal, they can be ignored directly. So the final version of the program is as follows:
/** * @param {number[][]} A * @return {number[][]} */ var flipAndInvertImage = function(A) { for (let i = 0; i < A.length; i++) { let j = 0, k = A[i].length - 1 while (j < k) { if (A[i][j] === A[i][k]) { A[i][j] ^= 1 A[i][k] ^= 1 } j++, k-- } if (j === k) { A[i][j] ^= 1 } } return A };
- Time complexity: O(n * k / 2)
- Spatial complexity: O(1)
Origin address: https://leetcode-cn.com/probl...
The code is updated from time to time. Welcome star and me. repo
Scanning the two-dimensional code below or searching for "Teacher tony's Front-end Tutorial" to pay attention to my Wechat Public Number, you can receive my latest article as soon as possible.