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;
}

 Leetcode832. Flipping an Image 随笔

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

 

常规思路 对每个元素进行处理 时间复杂度为n`2

Explanation:

  1. reverse every row.
  2. toggle every value.

 

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; }
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄