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有限,所以没有打败的百分比。