首页 > 其他 > 详细

Leetcode832. Flipping an Image

时间:2020-01-18 10:07:13      阅读:62      评论:0      收藏:0      [点我收藏+]

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

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

Leetcode832. Flipping an Image

原文:https://www.cnblogs.com/chengxian/p/12208056.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!