Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit22ca144

Browse files
authored
Create printElementsInSpiralOrder
1 parent2b41cf2 commit22ca144

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

‎printElementsInSpiralOrder‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
static String printElementsInSpiralOrder(int[][] matrix) { //time complexity: O(n)
2+
String result = null;
3+
List ans = new ArrayList<>();
4+
if(matrix.length != 0){
5+
int r1 = 0, r2 = matrix.length-1;
6+
int c1 = 0, c2 = matrix[0].length-1;
7+
while(r1<=r2 && c1<=c2){
8+
for(int c=c1;c<=c2;c++)
9+
ans.add(matrix[r1][c]);
10+
for(int r = r1+1;r<=r2;r++)
11+
ans.add(matrix[r][c2]);
12+
13+
if(r1<r2 && c1<c2){
14+
for(int c = c2-1;c> c1;c--)
15+
ans.add(matrix[r2][c]);
16+
for(int r=r2;r> r1;r--)
17+
ans.add(matrix[r][c1]);
18+
}
19+
r1++;
20+
r2--;
21+
c1++;
22+
c2--;
23+
24+
}
25+
}
26+
result = ans.toString().replace(",", "");
27+
return result;
28+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp