
내가 작성한 코드
import java.util.*;
class Solution {
public int[] solution(int n) {
int[][] triangle = new int[n][n];
int x = -1, y = 0; // 시작 위치는 첫 이동이 아래로 가기 때문에 (-1,0)
int num = 1; // 채워야 할 숫자
int direction = 0; // 0: 아래, 1: 오른쪽, 2: 왼쪽 위
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) { // 한 방향에서 채워야 하는 칸 수는 점점 줄어듦
if (direction == 0) { // 아래로
x++;
} else if (direction == 1) { // 오른쪽으로
y++;
} else if (direction == 2) { // 왼쪽 위로
x--;
y--;
}
triangle[x][y] = num++;
}
direction = (direction + 1) % 3; // 방향 전환
}
// 결과 배열 만들기 (삼각형이므로 [i][j]에서 j <= i인 것만 사용)
List<Integer> result = new ArrayList<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
result.add(triangle[i][j]);
}
}
return result.stream().mapToInt(i -> i).toArray();
}
}
다른 사람의 코드
class Solution {
public int[] solution(int n) {
int[][] li = new int[n][n];
int x = 0, y = 0;
int step = n;
int value = 1;
while (step > 0) {
/* 아래로 이동 */
for (int i = step; i > 0; i--) {
li[x++][y] = value++;
}
x--; // 행 복귀
y++; // 로테이션
step--; // 스텝 업데이트
/* 오른쪽 이동 */
for (int i = step; i > 0; i--) {
li[x][y++] = value++;
}
y--; // 열 복귀
x--; // 로테이션
y--; // 로테이션
step--;
/* 북서쪽 이동 */
for (int i = step; i > 0; i--) {
li[x--][y--] = value++;
}
x++; // 행 복귀
y++; // 열 복귀
x++; // 로테이션
step--;
}
int[] answer = new int[n * (n + 1) / 2]; // value - 1과 같은 듯
int size = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (li[i][j] == 0)
break;
answer[size++] = li[i][j];
}
}
return answer;
}
}
Share article