zoukankan      html  css  js  c++  java
  • 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有限,所以没有打败的百分比。

  • 相关阅读:
    sql server 2005中的用户自定义函数
    sql去除读出来的字段中的空格
    分割字符串
    VS2008 安装失败(microsoft visual studio web 创作组件 安装失败)的解决方法
    SAXParserFactory之求解
    Sql中的decimal
    设置fileupload上传文件的大小
    通过正则表达式来判断字符串是否为数字组成的
    ERP,CRM,BI的定义
    英语基本句型
  • 原文地址:https://www.cnblogs.com/chenjx85/p/9061420.html
Copyright © 2011-2022 走看看