문제 설명
해결과정
Solution.java
import java.util.*;
class Solution {
public int[] solution(int n) {
int[] answer = new int [n*(n+1)/2];
LinkedList<LinkedList<Integer>> list = new LinkedList<>();
int number = 1;
for(int i = 1; i <= n; i++) {
int cnt = i;
LinkedList<Integer> index = new LinkedList<>();
while(cnt != 0) {
index.add(number);
number++;
cnt--;
}
list.add(index);
}
number = 1;
while(number < answer.length+1) {
// 수직 수평
for(int i = 0; i < list.size(); i++) {
LinkedList<Integer> index = list.get(i);
if(i == list.size()-1) {
while(index.size() != 0) {
answer[index.removeFirst()-1] = number++;
}
} else {
answer[index.removeFirst()-1] = number++;
}
}
removeList(list);
// 사선
for(int i = list.size()-1; 0 <= i ; i--) {
LinkedList<Integer> index = list.get(i);
answer[index.removeLast()-1] = number++;
}
removeList(list);
// for(int i = 0; i < list.size(); i++) {
// LinkedList<Integer> index = list.get(i);
// if(i == list.size()-1) {
// while(index.size() != 0) {
// answer[index.removeFirst()-1] = number++;
// }
// } else {
// answer[index.removeFirst()-1] = number++;
// }
// }
}
return answer;
}
public void removeList(LinkedList<LinkedList<Integer>> list) {
int i = 0;
while(i < list.size()) {
LinkedList<Integer> index = list.get(i);
if(index.size() == 0) {
list.remove(i);
} else {
i++;
}
}
}
public void printAllList(LinkedList<LinkedList<Integer>> list){
for(LinkedList<Integer> index : list) {
for(int i : index) {
System.out.print(i + " ");
}
System.out.println();
}
}
}
Java
복사