[PHP In Leetcode 832] Flipping an Image

版权声明:Edited by I Hsien https://blog.csdn.net/POTASSIUM711/article/details/88723602

题目

Given a binary matrix A, we want to 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].

给定一个二进制矩阵 A,我们想先水平翻转图像,然后反转图像并返回结果。
水平翻转图片就是将图片的每一行都进行翻转,即逆序。例如,水平翻转 [1, 1, 0] 的结果是 [0, 1, 1]。
反转图片的意思是图片中的 0 全部被 1 替换, 1 全部被 0 替换。例如,反转 [0, 1, 1] 的结果是 [1, 0, 0]。

示例 1:
输入: [[1,1,0],[1,0,1],[0,0,0]]
输出: [[1,0,0],[0,1,0],[1,1,1]]
解释: 首先翻转每一行: [[0,1,1],[1,0,1],[0,0,0]];
然后反转图片: [[1,0,0],[0,1,0],[1,1,1]]
示例 2:
输入: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
输出: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
解释: 首先翻转每一行: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]];
然后反转图片: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]

说明:
1 <= A.length = A[0].length <= 20
0 <= A[i][j] <= 1


思路

为了节约时间,只遍历一半的数组长度,将遍历到的元素和尾端相应的交换.并在交换的时候取反.
值得注意的是对于中间的元素的转换.在数组长度为奇数时中间的要额外取反.


代码

class Solution {
    /**
     * @param Integer[][] $A
     * @return Integer[][]
     */
    function flipAndInvertImage($A) {
        $row=count($A);
        $column=count($A[0]);
        for($i=0;$i<$row;$i++)
        {
            for($j=0;$j<$column/2;$j++)
            {
                $temp=$A[$i][$j];
                $A[$i][$j]=$A[$i][$column-1-$j];
                $A[$i][$column-1-$j]=$temp;
                if($A[$i][$j]==0)
                    $A[$i][$j]=1;
                else
                    $A[$i][$j]=0;
                if($A[$i][$column-1-$j]==0)
                    $A[$i][$column-1-$j]=1;
                else
                    $A[$i][$column-1-$j]=0;   
            }
             if($column%2==1)
                { 
                    if($A[$i][$column/2]==0)
                    $A[$i][$column/2]=1;
                    else
                    $A[$i][$column/2]=0; 
                }
        }
      return $A  ;
    }    
}

性能情况和总结

在这里插入图片描述
运行时间在前25%的代码是求反和交换同时进行,有一定的改进.

class Solution {
    function flipAndInvertImage($A) {
        $res = [];
        for($i=0,$len=count($A);$i<$len;$i++){
            $item_arr = &$A[$i];
            for($j=0,$item_arr_len = count($item_arr);$j<$item_arr_len/2;$j++){
                $item = $item_arr[$j] ^ 1;
                $item_arr[$j] = $item_arr[$item_arr_len - $j - 1] ^ 1;
                $item_arr[$item_arr_len - $j - 1] = $item;
            }
        }
        return $A;
    }
}

代码要注意压缩,减少不必要的变量开销.

猜你喜欢

转载自blog.csdn.net/POTASSIUM711/article/details/88723602
今日推荐