832. Flipping an Image

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;
}
原文地址:https://www.cnblogs.com/okokabcd/p/9420445.html