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
總結
以上是生活随笔為你收集整理的leetcode-832-Flipping an Image的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springmvc配置同时支持html和
- 下一篇: 股票入门书籍 股票市场入门书籍