File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed
Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+ class Solution {
3+ public int [] solution (int n ) {
4+ int [][] arr = new int [n][];
5+ for (int i = 0 ; i< n ;i++ ){
6+ arr[i] = new int [i+ 1 ];
7+ }
8+ int row = 0 , col = 0 ;
9+ int num = 1 ;
10+ int total = n* (n+ 1 )/ 2 ;
11+ int state = 0 ; // 0:down, 1:right, 2:up
12+ while (num <= total){
13+ arr[row][col] = num++ ;
14+ if (state == 0 ){
15+ if (row+ 1 == n || arr[row+ 1 ][col] != 0 ){
16+ state = 1 ;
17+ col++ ;
18+ }else {
19+ row++ ;
20+ }
21+ }else if (state == 1 ){
22+ if (col == row || arr[row][col+ 1 ] != 0 ){
23+ state = 2 ;
24+ row-- ;
25+ col-- ;
26+ }else {
27+ col++ ;
28+ }
29+ }else if (state == 2 ){
30+ if (arr[row- 1 ][col- 1 ] != 0 ){
31+ state = 0 ;
32+ row++ ;
33+ }else {
34+ row-- ;
35+ col-- ;
36+ }
37+ }
38+ }
39+
40+ int [] answer = new int [total];
41+ int idx = 0 ;
42+ for (int i = 0 ; i< n; i++ ){
43+ for (int j = 0 ; j< arr[i]. length; j++ ){
44+ answer[idx++ ] = arr[i][j];
45+ }
46+ }
47+ return answer;
48+ }
49+ }
50+ ```
You can’t perform that action at this time.
0 commit comments