前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode-832-Flipping an Image

leetcode-832-Flipping an Image

作者头像
chenjx85
发布2018-05-21 18:13:55
7820
发布2018-05-21 18:13:55
举报

题目描述:

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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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、题意清晰,这是一道简单题,直接暴力解法。

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

代码语言:javascript
复制
    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有限,所以没有打败的百分比。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-05-19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
  • 要完成的函数:
  • 说明:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档