public int[][] flipAndInvertImage(int[][] A) {
for (int i = 0; i < A.length; i++) {
for (int j = 0; j <A[0].length / 2; j++) {
int temp = A[i][j];
A[i][j] = A[i][A[0].length - 1 - j];
A[i][A[0].length - 1 - j] = temp;
}
}
for(int i=0;i<A.length;i++){
for(int j=0;j<A.length;j++){
if (A[i][j]%2==0)
A[i][j]=1;
else A[i][j]=0;
// System.out.print(A[i][j]+" ");
}
// System.out.println();
}
return A;
}
常规思路 对每个元素进行处理 时间复杂度为n`2
In Java, I did both steps together:
Compare the i
th and n - i - 1
th in a row.
The "trick" is that if the values are not the same,
but you swap and flip, nothing will change.
So if they are same, we toggle both, otherwise we do nothing.
public int[][] flipAndInvertImage(int[][] A) {
int n = A.length;
for (int[] row : A)
for (int i = 0; i * 2 < n; i++)
if (row[i] == row[n - i - 1])
row[i] = row[n - i - 1] ^= 1;
return A;
}
Leetcode832. Flipping an Image
原文:https://www.cnblogs.com/chengxian/p/12208056.html