[leetcode][easy][Array][832]Flipping an Image]
阿新 • • 發佈:2018-12-17
Flipping an Image
題目連結
題目描述
給定一個二維矩陣A
。翻轉它,並取反,返回結果。
注:
- 翻轉:顛倒圖片每行。例如
[1, 1, 0]
變為[0, 1, 1]
。 - 取反:所有的
0
換成1,所有的1
換成0。
約定
1 <= A.length = A[0].length <= 20
0 <= A[i][j] <= 1
示例
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]]
解答
解答1
class Solution { public: vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) { int rowNum = A.size(); int colNum = A[0].size(); int colMid = (colNum+1)/2; //按行遍歷 for (int rowIndex = 0; rowIndex < rowNum; rowIndex++) { for (int colIndex = 0; colIndex < colMid; colIndex++) { int temp = A[rowIndex][colIndex]; A[rowIndex][colIndex] = A[rowIndex][colNum - colIndex - 1] == 1 ? 0 : 1; A[rowIndex][colNum - colIndex - 1] = temp == 1 ? 0 : 1; } } return A; } };
以上程式碼比較簡潔,耗時16ms。
解答2
class Solution { public: vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) { flip(A); invert(A); return A; } private: void flip(vector<vector<int>>& A) { int rowNum = A.size(); int colNum = A[0].size(); //按行遍歷 for (int rowIndex = 0; rowIndex < rowNum; rowIndex++) { for (int colIndex = 0; colIndex < colNum/2; colIndex++) { int temp = A[rowIndex][colIndex]; A[rowIndex][colIndex] = A[rowIndex][colNum - colIndex - 1]; A[rowIndex][colNum - colIndex - 1] = temp; } } } void invert(vector<vector<int>>& A) { int rowNum = A.size(); int colNum = A[0].size(); for (int rowIndex = 0; rowIndex < rowNum; rowIndex++) { for (int colIndex = 0; colIndex < colNum; colIndex++) { A[rowIndex][colIndex] = A[rowIndex][colIndex] == 1 ? 0 : 1; } } } };
此種方法不太簡潔,但耗時8ms,超過99.5%。