-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_0059.java
More file actions
36 lines (29 loc) · 1.03 KB
/
_0059.java
File metadata and controls
36 lines (29 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.github.aditya;
public class _0059 {
// 0 ms, faster than 100.00%, memory 40.6 MB, less than 82.02%
// Time Complexity O(n*n) and Space Complexity O(1)
class Solution {
public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
int num = 1;
int top = 0, bottom = n - 1, left = 0, right = n - 1;
while (top <= bottom && left <= right) {
for (int i = left; i <= right; i++)
result[top][i] = num++;
top++;
for (int i = top; i <= bottom; i++)
result[i][right] = num++;
right--;
if (top > bottom || left > right)
break;
for (int i = right; i >= left; i--)
result[bottom][i] = num++;
bottom--;
for (int i = bottom; i >= top; i--)
result[i][left] = num++;
left++;
}
return result;
}
}
}