https://school.programmers.co.kr/learn/courses/30/lessons/68645
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
결국 배열의 인덱스만 잘 조절하면 쉽게 풀 수 있을 것이다.
다소 복잡해보이는 로직은 ide에서 디버깅을 찍어가며 놓치고 있는 부분이 있는지 확인해주면 좋다.
import java.util.*;
class Solution {
public int[] solution(int n) {
int[] answer = {};
List<Integer[]> list = new ArrayList<>();
int index = 1;
int endNum = 0;
for (int i = 0; i < n; i++) {
endNum += index;
Integer[] arr = new Integer[index];
for (int j = 0; j < index; j++) {
arr[j] = null;
}
list.add(arr);
index++;
}
answer = new int[endNum];
int curNum = 1;
int loop = n;
int listIndex = 0;
int startIndex = 0;
int curIndex = 0;
while (loop != 0) {
for (int i = 0; i < loop; i++) {
list.get(listIndex)[startIndex] = curNum;
curNum++;
listIndex++;
}
listIndex--;
loop--;
if(loop == 0) break;
startIndex++;
curIndex = startIndex;
for(int i = 0; i < loop; i++) {
list.get(listIndex)[curIndex] = curNum;
curIndex++;
curNum++;
}
loop--;
if(loop == 0) break;
curIndex--;
for(int i = 0; i < loop; i++) {
listIndex--;
curIndex--;
list.get(listIndex)[curIndex] = curNum;
curNum++;
}
loop--;
listIndex++;
}
int arrIndex = 0;
for(int i = 0; i < list.size(); i++) {
int size = list.get(i).length;
for(int j = 0; j < size; j++) {
answer[arrIndex] = list.get(i)[j];
arrIndex++;
}
}
return answer;
}
}
'알고리즘 > Lv2. 프로그래머스' 카테고리의 다른 글
[프로그래머스] 구명보트 -JAVA (0) | 2024.08.06 |
---|---|
[프로그래머스] 혼자놀기의달인 -JAVA (0) | 2024.07.31 |
[프로그래머스] 줄 서는 방법-JAVA (2) | 2024.07.22 |
[프로그래머스] 2 x n 타일링 -JAVA (0) | 2024.07.18 |
[프로그래머스] 124 나라의 숫자 -JAVA (0) | 2024.07.17 |