[PHP In Leetcode 832] Flipping an Image

题目

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;
    }
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值