LeetCode 832. Flipping an Image

Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image.

To flip an image horizontally means that each row of the image is reversed.

  • For example, flipping [1,1,0] horizontally results in [0,1,1].

To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.

  • For example, inverting [0,1,1] results in [1,0,0].

Example 1:

Input: image = [[1,1,0],[1,0,1],[0,0,0]]
Output: [[1,0,0],[0,1,0],[1,1,1]]
Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].
Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]

Example 2:

Input: image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].
Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]

Constraints:

  • n == image.length
  • n == image[i].length
  • 1 <= n <= 20
  • images[i][j] is either 0 or 1.

这题要把一个0/1的2d array先横着倒过来,再把每个元素的0/1反过来,其实很直观很简单,就算是in place也很简单,于是就很快写出了代码。我的思路就是对每一行都用2 pointers指向前后,用一个temp来swap就行了,赋值的时候顺便取反。然后看了solutions里大家的思路,太强了,可以不需要temp直接判断前后两个数字一不一样,不一样啥也不用干,一样的话各自取反就行了。太妙了。

class Solution {
    public int[][] flipAndInvertImage(int[][] image) {
        int row = image.length;
        int col = image[0].length;

        for (int i = 0; i < row; i++) {
            int start = 0;
            int end = col - 1;
            while (start <= end) {
                int temp = image[i][start];
                image[i][start] = image[i][end] == 0 ? 1 : 0;
                image[i][end] = temp == 0 ? 1 : 0;
                start++;
                end--;
            }
        }
        return image;
    }
}

你可能感兴趣的:(LeetCode,leetcode)