LintCode 题解丨谷歌面试题:翻转像素

一张图片以二维数组byte[][]形式的像素点来排列,数组的每一个元素代表一个像素位(0 或 1)。现在需要将这些像素点翻转,首先将每一行的像素点对称翻转,然后将每一位上的像素点翻转(0->1,1->0)。

样例1

输入: byte[][]= [[1,0,1,1,0],[0,1,1,0,1],[1,1,0,1,0],[0,0,1,0,0]]
输出: byte[][]= [[1,0,0,1,0],[0,1,0,0,1],[1,0,1,0,0],[1,1,0,1,1]]
样例说明: 首先我们把每一行的像素点对称反转,变为[[0,1,1,0,1],[1,0,1,1,0],[0,1,0,1,1],[0,0,1,0,0]]. 
然后我们把每一位进行翻转,得到答案[[1,0,0,1,0],[0,1,0,0,1],[1,0,1,0,0],[1,1,0,1,1]].

样例2

Input: byte[][]= [[1],[0],[1]]
Output: byte[][]= [[0],[1],[0]]
Explanation: 首先我们把每一行的像素点对称反转,变为[[1],[0],[1]]. 然后我们把每一位进行翻转,
得到答案[[0],[1],[0]].

【题解】

本题分为两个子任务,第一个子任务,队伍每一个序列,进行反转即可,反转的时候按正序和倒序对应位置交换。第二个子任务,直接01互换,判断即可。

public
class Solution {
    /**
     * @param Byte:
     * @return: return the answer after flipped
     */
public
    int[][] flippedByte(int[][] Byte) {
        // Write your code here
        for (int i = 0; i < Byte.length; i++) {
            int len = Byte[i].length;
            int temp;
            for (int j = 0; j < len / 2; j++) {
                temp = Byte[i][j];
                Byte[i][j] = Byte[i][len - j - 1];
                Byte[i][len - j - 1] = temp;
            }
        }
        for (int i = 0; i < Byte.length; i++) {
            for (int j = 0; j < Byte[i].length; j++) {
                if (Byte[i][j] == 0)
                    Byte[i][j] = 1;
                else
                    Byte[i][j] = 0;
                // System.out.print(Byte[i][j]+" ");
            }
            // System.out.println();
        }
        return Byte;
    }
}

你可能感兴趣的:(LintCode 题解丨谷歌面试题:翻转像素)