public class Solution {
public int[][] FlipAndInvertImage(int[][] image) {
foreach (var row in image) {
for (var col = 0; col < row.Length / 2; ++col) {
// shorthand:
(row[col], row[^(col+1)]) = (row[^(col+1)], row[col]);
// longhand:
// (row[col], row[row.Length - (col+1)]) = (row[row.Length - (col+1)], row[col]);
}
for (var col = 0; col < row.Length; ++col) {
row[col] ^= 1;
}
}
return image;
}
}
Optimized:
public class Solution {
public int[][] FlipAndInvertImage(int[][] image) {
foreach (var row in image) {
var half = row.Length / 2;
for (var col = 0; col < half; ++col) {
// shorthand:
(row[col], row[^(col+1)]) = (row[^(col+1)] ^ 1, row[col] ^ 1);
// longhand:
// (row[col], row[row.Length - (col+1)]) = (row[row.Length - (col+1)], row[col]);
}
}
if (image.Length > 0 && image[0].Length % 2 == 1) {
var middle = image[0].Length / 2;
foreach (var row in image) {
row[middle] ^= 1;
}
}
return image;
}
}
Source:
https://leetcode.com/problems/flipping-an-image/
No comments:
Post a Comment