[프로그래머스] [Java] 삼각 달팽이
2021. 4. 3. 12:29ㆍ알고리즘/프로그래머스
728x90
반응형
SMALL
문제 설명
정수 n이 매개변수로 주어집니다.
다음 그림과 같이 밑변의 길이와 높이가 n인 삼각형에서 맨 위 꼭짓점부터 반시계 방향으로 달팽이 채우기를 진행한 후,
첫 행부터 마지막 행까지 모두 순서대로 합친 새로운 배열을 return 하도록 solution 함수를 완성해주세요.
제한사항
- n은 1 이상 1,000 이하입니다.
입출력 예
n | result |
4 | [1,2,9,3,10,8,4,5,6,7] |
5 | [1,2,12,3,13,11,4,14,15,10,5,6,7,8,9] |
6 | [1,2,15,3,16,14,4,17,21,13,5,18,19,20,12,6,7,8,9,10,11] |
🌈 Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
class Solution {
public int[] solution(int n) {
/* 높이가 n인 삼각형 생성 */
int[][] triangle = new int[n][];
for (int i = 0; i < triangle.length; i++) {
triangle[i] = new int[i + 1];
}
int x = -1, y = 0;
int index = 1;
for (int i = 0; i < triangle.length; i++) {
for (int j = i; j < triangle.length; j++) {
if (i % 3 == 0) {
x++;
} else if (i % 3 == 1) {
y++;
} else {
x--;
y--;
}
triangle[x][y] = index++;
}
}
int[] answer = new int[(n * (n + 1)) / 2];
int k = 0;
for (int i = 0; i < triangle.length; i++) {
for (int j = 0; j < triangle[i].length; j++) {
answer[k++] = triangle[i][j];
}
}
return answer;
}
}
|
cs |
👩💻 풀어보기 👨💻 https://programmers.co.kr/learn/courses/30/lessons/68645
728x90
반응형
LIST
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] [Java] 음양 더하기 (0) | 2021.05.17 |
---|---|
[프로그래머스] [Java] 순위 검색 (0) | 2021.04.06 |
[프로그래머스] [Java] 행렬의 곱셈 (0) | 2021.03.27 |
[프로그래머스] [Java] 문자열 내 마음대로 정렬하기 (0) | 2021.03.27 |
[프로그래머스] [Java] 체육복 (0) | 2021.03.27 |