Thursday, April 27, 2017
48. Rotate Image
Version #1 Rotate + Recursion
四刷
Fastest ever -> only 19mins to bug freely pass
主要是非常机智的直接把left,right,top,bottom都写下来了,这样就不会有任何的typo了
98.41 %
class Solution {
public void rotate(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return;
// rotate by layer
helper(matrix, 0, matrix.length);
}
private void helper(int[][] matrix, int offset, int N) {
int left = offset, right = N - offset - 1;
int top = offset, bottom = N - offset - 1;
if (left >= right) return;
for (int i = 0; left + i < right; i++) {
int temp = matrix[top][left + i];
matrix[top][left + i] = matrix[bottom - i][left];
matrix[bottom - i][left] = matrix[bottom][right - i];
matrix[bottom][right - i] = matrix[top + i][right];
matrix[top + i][right] = temp;
}
helper(matrix, offset + 1, N);
}
}
三刷
100.00 %
class Solution {
public void rotate(int[][] matrix) {
helper(matrix, 0, matrix.length);
}
private void helper(int[][] matrix, int j, int N) {
int width = N - 2 * j;
if (width < 2) {
return;
}
for (int i = 0; i < width - 1; i++) {
int temp = matrix[j][j + i];
matrix[j][j + i] = matrix[j + width - 1- i][j];
matrix[j + width - 1 - i][j] = matrix[j + width - 1][j + width - 1 - i];
matrix[j + width - 1][j + width - 1 - i] = matrix[j + i][j + width - 1];
matrix[j + i][j + width - 1] = temp;
}
helper(matrix, j + 1, N);
}
}
Version #2 Swap for 2 times
59.34 %
class Solution {
public void rotate(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return;
int rows = matrix.length;
int cols = matrix[0].length;
for (int y = 0; y < cols; y++) {
for (int x = 0; x < rows / 2; x++) {
int temp = matrix[x][y];
matrix[x][y] = matrix[rows - x - 1][y];
matrix[rows - x - 1][y] = temp;
}
}
for (int x = 0; x < rows; x++) {
for (int y = 0; y < x; y++) {
int temp = matrix[x][y];
matrix[x][y] = matrix[y][x];
matrix[y][x] = temp;
}
}
}
}
Version #1 Recursion
72.77 %
烦死了这道题。。。。就是一直倒倒倒
想清楚这个size的定义
public class Solution {
public void rotate(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return;
rotate(matrix, matrix.length, 0);
}
private void rotate(int[][] matrix, int size, int offset) {
if (size <= 1) return;
for (int i = 0; i < size - 1; i++) {
int temp = matrix[offset][offset + i];
matrix[offset][offset + i] = matrix[offset + size - 1 - i][offset];
matrix[offset + size - 1 - i][offset] = matrix[offset + size - 1][offset + size - 1 - i];
matrix[offset + size - 1][offset + size - 1 - i] = matrix[offset + i][offset + size - 1];
matrix[offset + i][offset + size - 1] = temp;
}
rotate(matrix, size - 2, offset + 1);
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment