1. 程式人生 > >leetcode (Flipping an Image)

leetcode (Flipping an Image)

Title:Flipping an Image   832

Difficulty:Easy

原題leetcode地址:https://leetcode.com/problems/flipping-an-image/

 

1.  先反轉再取反

時間複雜度:O(n^2),巢狀for迴圈,需要遍歷整個陣列。

空間複雜度:O(1),沒有申請額外的空間。

    /**
     * 先反轉再取反
     * @param A
     * @return
     */
    public static int[][] flipAndInvertImage(int[][] A) {

        for (int i = 0; i < A.length; i++) {
            int startIndex = 0;
            int endIndex = A.length - 1;
            while (startIndex < endIndex) {
                int tmp = A[i][startIndex];
                A[i][startIndex] = A[i][endIndex];
                A[i][endIndex] = tmp;
                startIndex++;
                endIndex--;
            }
        }

        for (int i = 0; i < A.length; i++) {
            for (int j = 0; j < A[0].length; j++) {
                A[i][j] = A[i][j] ^ 1;
            }
        }

        return A;

    }

2.  先取反再反轉

時間複雜度:O(n^2),巢狀for迴圈,需要遍歷整個陣列。

空間複雜度:O(1),沒有申請額外的空間。

    /**
     * 先取反再反轉
     * @param A
     * @return
     */
    public static int[][] flipAndInvertImage1(int[][] A) {

        int col = A[0].length;

        for (int[] rows: A) {
            for (int i = 0; i < (col + 1) / 2; i++) {
                int tmp = rows[i] ^ 1;
                rows[i] = rows[col - 1 - i] ^ 1;
                rows[col - 1 - i] = tmp;
            }
        }

        return A;

    }