inblog logo
|
LHS's Study Space
    알고리즘문제풀기프로그래머스

    [프로그래머스] 삼각 달팽이(68645)

    lhs's avatar
    lhs
    Dec 30, 2024
    [프로그래머스] 삼각 달팽이(68645)
    Contents
    1. 문제 풀이 아이디어2. 나의 정답 코드3. 정리4. 다른 사람의 코드 리뷰
    school.programmers.co.kr
    https://school.programmers.co.kr/learn/courses/30/lessons/68645
     

    1. 문제 풀이 아이디어

    • 이동 패턴을 기반으로 배열을 채우면 문제를 해결할 수 있다.

    2. 나의 정답 코드

    class Solution { public int[] solution(int n) { int[] answer = new int[n * (n + 1) / 2]; int pat = 0; int num = 1; int index = 0; answer[index] = num++; while (num <= answer.length) { if (pat % 3 == 0) { int count = pat == 0 ? 1 : 0; while (index + count + pat * 2 / 3 < answer.length && answer[index + count + pat * 2 / 3] == 0) { index += count + pat * 2 / 3; answer[index] = num++; count++; } } else if (pat % 3 == 1) { while (index + 1 < answer.length && answer[index + 1] == 0) { index++; answer[index] = num++; } } else { int count = 0; while (answer[index + count - n + pat / 3] == 0) { index += count - n + pat / 3; answer[index] = num++; count++; } } pat++; } return answer; } }

    3. 정리

    • 결과 배열의 크기를 n * (n + 1) / 2로 초기화한다.
    • num이 배열 크기와 같아질 때까지 값을 채운다.
    • 각 패턴은 pat % 3을 이용해 계산하고, 해당 패턴에 따라 숫자를 배열에 넣는다.

    4. 다른 사람의 코드 리뷰

    class Solution { public int[] solution(int n) { int[] answer = new int[(n*(n+1))/2]; int[][] matrix = new int[n][n]; int x = -1, y = 0; int num = 1; for (int i = 0; i < n; ++i) { for (int j = i; j < n; ++j) { if (i % 3 == 0) { ++x; } else if (i % 3 == 1) { ++y; } else if (i % 3 == 2) { --x; --y; } matrix[x][y] = num++; } } int k = 0; for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { if(matrix[i][j] == 0) break; answer[k++] = matrix[i][j]; } } return answer; } }
    • 2차원 배열을 활용하여 이동 패턴을 더 간단하게 구현하였다.
    Share article
    Contents
    1. 문제 풀이 아이디어2. 나의 정답 코드3. 정리4. 다른 사람의 코드 리뷰

    LHS's Study Space

    RSS·Powered by Inblog