Topic describes
Analysis of the topic
We need to reverse each subarray first, then replace 0 –> 1 and 1 –> 0. 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
};
Copy the code
To optimize the
For 0 –> 1 and 1 –> 0 substitutions, we don’t need the ternary operators, but xOR operators. We can simplify the code 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) {
[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
};
Copy the code
The advanced
Looking closely at the test case provided in the question, we found that the left and right numbers are not equal and can be directly ignored, 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
};
Copy the code
- Time complexity:
O(n * k / 2)
- Spatial complexity:
O(1)
Original address: leetcode-cn.com/problems/fl… Code updates irregularly, welcome star my repo
Scan the QR code below or search for “Teacher Tony’s front-end cram school” to follow my wechat official account, and then you can receive my latest articles in the first time.