目前刚看完数组的基础篇,再看数组的基础题目,这次的题目是832题,属于简单类型
https://leetcode.com/problems/flipping-an-image/
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
第一次代码提交
第一次我重新定义了一个新的二维数组,用来存放,所以就会特别的麻烦。
//1. 第一版
public static int[][] flipAndInvertImage(int[][] A) {
int m = A.length;
if (m == 0) return A;
int n = A[0].length == 0 ? 0 : A[0].length;
int[][] B = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
B[i][j] = A[i][j];
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
B[i][A[i].length - 1 - j] = A[i][j] == 1 ? 0 : 1;
}
}
return B;
}
第二版
这一版进行了更新,我直接在数组A上面进行了操作,这样不用重新定义数组B,不需要开辟数组A那么大得一块儿空间
//2.第二版
public static int[][] flipAndInvertImage(int[][] A) {
int m = A.length;
if (m == 0) return A;
int n = A[0].length == 0 ? 0 : A[0].length - 1;
int temp;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n / 2 + 1; j++) {
temp = A[i][j];
A[i][j] = A[i][n - j] == 0 ? 1 : 0;
A[i][n - j] = temp == 0 ? 1 : 0;
}
}
return A;
}
第三版
最后一版,我又画了for循环,这样看起来更加清晰,操作起来更加的方便。
// 3. 第三版
public static int[][] flipAndInvertImage(int[][] A) {
int m = A.length;
if (m == 0) return A;
int temp, n;
for (int nums[] : A) {
n = nums.length - 1;
for (int j = 0; 2 * j <= n; j++) {
temp = nums[j];
nums[j] = nums[n - j] == 0 ? 1 : 0;
nums[n - j] = temp == 0 ? 1 : 0;
}
}
return A;
}
总结
三次提交代码的性能都有变化,可以从这其中发现很多可以优化的地方,也很有意思
下面这是三次散发性能的结果
不同语言对比
有大神给出了三种语言的代码,完全体现出了py代码的简洁,还体现出了Java代码巧妙地利用方式