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].

Example 1:

Input: [[1,1,0],[1,0,1],[0,0,0]]
Output: [[1,0,0],[0,1,0],[1,1,1]]
Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].
Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]

Example 2:

Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].
Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]

Notes:

  • 1 <= A.length = A[0].length <= 20
  • 0 <= A[i][j] <= 1

 

要完成的函数:

vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) 

 

说明:

1、这道题目给定一个二维的vector,里面的元素是1或者0,要求把每一行的元素第一个和最后一个交换位置,第二个和倒数第二个元素交换位置,依此类推……并且对每个元素都做非操作——把1变成0,把0变成1.

2、题意清晰,这是一道简单题,直接暴力解法。

代码如下,分享给大家,附详解:

    vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) 
    {
        int row=A.size(),col=A[0].size(),t;//t是临时变量
        for(int i=0;i<row;i++)
        {
            for(int j=0;j<col/2;j++)//j<col/2,交换两个元素的值,并且做非操作
            {
                t=A[i][col-j-1];
                A[i][col-j-1]=!A[i][j];
                A[i][j]=!t;
            }
        }
        if(col%2==1)//当列数为奇数的时候,需要特别处理col/2这个元素,做一下非操作
        {
            for(int i=0;i<row;i++)
                A[i][col/2]=!A[i][col/2];
        }
        return A;
    }

上述代码实测14ms,由于服务器接收到的cpp submissions有限,所以没有打败的百分比。

 

转载于:https://www.cnblogs.com/chenjx85/p/9061420.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值