Leetcode 832. Flipping an Image
The problem requires us to flip an image horizontally and then invert it.
Flipping horizontally means that each row of the image is reversed. For example, if the row is [1, 0, 1]
, after flipping, it will be [1, 0, 1]
.
Inverting means that each 0 is replaced by 1 and each 1 is replaced by 0. Continuing with the previous example, after inverting, [1, 0, 1]
becomes [0, 1, 0]
.
Given an n x n
binary matrix image
, we need to return the resulting matrix after performing both operations.
Example:
Input: image = [[1,1,0],[1,0,1],[0,0,0]]
Output: [[1,0,0],[0,1,0],[1,1,1]]
n x n
matrix, so we will assume it is true unless specified otherwise.public class Solution {
public int[][] flipAndInvertImage(int[][] image) {
for (int[] row : image) {
int length = row.length;
// Flip the row by swapping elements from both ends up to the middle
for (int i = 0; i < (length + 1) / 2; i++) {
// Swap and invert the values
int temp = row[i] ^ 1; // Invert while saving
row[i] = row[length - 1 - i] ^ 1; // Invert while assigning
row[length - 1 - i] = temp;
}
}
return image;
}
}
n
be the number of rows and each row also has n
columns.1
(^ 1
). This works because 1^1 = 0
and 0^1 = 1
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?