832. Flipping an Image - LeetCode

Posted okokabcd

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了832. Flipping an Image - LeetCode相关的知识,希望对你有一定的参考价值。

Question

832. Flipping an Image

技术分享图片

Solution

题目大意:将1列与最后n列对换,2列与n-1列对换…然后再将每个元素取反

思路:遍历二维数组的左半边,对每个元素先做对换再取反

Java实现:

public int[][] flipAndInvertImage(int[][] A) {
    // flip and reverse
    for (int row=0; row<A.length; row++) {
        for (int col=0; col<=A[row].length/2; col++) {
            if (col == A[row].length/2 && A[row].length%2 == 0) break;
            int end = A[row].length - 1 - col;
            int tmp = A[row][col];
            A[row][col] = invert(A[row][end]);
            A[row][end] = invert(tmp);
            System.out.print(A[row][col] + ", ");
        }
        System.out.println();
    }
    return A;
}

int invert(int x) {
    return x == 1 ? 0 : 1;
}

以上是关于832. Flipping an Image - LeetCode的主要内容,如果未能解决你的问题,请参考以下文章

832. Flipping an Image

832. Flipping an Image

Leetcode_easy832. Flipping an Image

[LeetCode] 832. Flipping an Image_Easy

832. Flipping an Image

[LeetCode&Python] Problem 832. Flipping an Image