二刷
An edge case is when left == right
26.58 %
class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int counter = 1;
// [1, 2]
// [4, 3]
for (int offset = 0; offset < Math.ceil(n / 2.0); offset++) {
int left = offset;
int right = n - 1 - offset;
int top = offset;
int bottom = n - 1 - offset;
// 1st row, left to right
if (left == right) {
matrix[top][left] = counter++;
}
for (int i = left; i < right; i++) {
matrix[top][i] = counter++;
}
for (int i = top; i < bottom; i++) {
matrix[i][right] = counter++;
}
for (int i = right; i > left; i--) {
matrix[bottom][i] = counter++;
}
for (int i = bottom; i > top; i--) {
matrix[i][left] = counter++;
}
}
return matrix;
}
}
一刷
Can be optimized! [TODO]
100.00 %
class Solution {
public int[][] generateMatrix(int n) {
if (n <= 0) return new int[0][0];
int[][] result = new int[n][n];
int counter = 0;
int left = 0;
int right = n - 1;
int top = 0;
int bottom = n - 1;
while (left <= right && top <= bottom) {
int x = left;
int y = top;
while (x <= right) {
counter++;
result[y][x] = counter;
// System.out.println(y + " " + x + " " + counter);
x++;
}
x = right;
y = top + 1;
while (y <= bottom) {
counter++;
result[y][x] = counter;
// System.out.println(y + " " + x + " " + counter);
y++;
}
y = bottom;
x = right - 1;
if (left != right && top != bottom) {
while (x >= left) {
counter++;
result[y][x] = counter;
// System.out.println(y + " " + x + " " + counter);
x--;
}
x = left;
y = bottom - 1;
while (y > top) {
counter++;
result[y][x] = counter;
// System.out.println(y + " " + x + " " + counter);
y--;
}
}
left++;
right--;
top++;
bottom--;
}
return result;
}
}
No comments:
Post a Comment