[프로그래머스] Level 2 삼각달팽이 (JAVA)

Jiwoo Kim·2021년 2월 20일
0

알고리즘 정복하기

목록 보기
25/85
post-thumbnail

문제


풀이

  1. value를 1부터 차례로 증가시키며 알맞은 인덱스에 넣는 방식으로 answer 배열을 채워 넣었다.
  2. directionDOWN, SIDE, UP 중 하나이다.
    • DOWN: indexindexGap만큼 증가한다.
    • SIDE: index가 1씩 증가한다.
    • UP: indexindexGap만큼 감소한다.
  3. 한 면에서의 remainingCount에 따라 방향을 바꾸어가며 적절한 인덱스 규칙을 적용했다.

코드

class Solution {
    
    private static final int DOWN = 0;
    private static final int SIDE = 1;
    private static final int UP = 2;

    public int[] solution(int n) {
        int[] answer = new int[n * (n + 1) / 2];
        int value = 1, index = 0, direction = DOWN;
        int indexGap = 0, remainingCount = n;
        while (n > 0) {
            remainingCount--;
            if (direction == DOWN) {
                index += indexGap;
                answer[index] = value++;
                indexGap++;
                if (remainingCount == 0) {
                    direction = SIDE;
                    remainingCount = --n;
                }
            } else if (direction == SIDE) {
                answer[++index] = value++;
                if (remainingCount == 0) {
                    direction = UP;
                    remainingCount = --n;
                }
            } else {
                index = index - indexGap;
                answer[index] = value++;
                indexGap--;
                if (remainingCount == 0) {
                    direction = DOWN;
                    remainingCount = --n;
                }
            }
        }
        return answer;
    }
}

참고

프로그래머스 - 삼각 달팽이(Java, LV2)

0개의 댓글