[프로그래머스] 덧칠하기 (Level 1)

유진·2024년 7월 10일
0

코딩테스트

목록 보기
1/18

📝 덧칠하기 (Level 1)

덧칠하기

🔸Java

  • 내가 작성한 코드
class Solution {
    public int solution(int n, int m, int[] section) {
        int answer = 0;
        int f = 0;
        boolean[] tmp = new boolean[n];
        for (int i = 0; i < n; i++) {
            tmp[i] = Boolean.TRUE;
        }
        for(int s = 0; s < section.length ; s++){
            f = section[s];
            tmp[f-1] = Boolean.FALSE;
        }
        for (int i = 0; i < n; i++){
            if ( tmp[i] == Boolean.FALSE ){
                for( int j = i; j < i+m; j++){
                    tmp[j] = Boolean.TRUE;
                }
                answer += 1;
            }
        }
        return answer;
    }
}

boolean으로 n만큼 길이의 배열을 선언하고 true로 채워넣었다. 그리고 section에 해당하는 부분은 false로 바꾸었다. 그리고 다시 배열을 처음부터 훑어 false인 부분에서 m 길이만큼 true로 바꿔주었다. false 반복문에서 true 처리가 끝나면 answer를 1 증가 시키도록 하였다.

하지만 실행하니 ArrayIndexOutOfBoundsException 에러가 발생했다. m길이만큼 true 바꿀때 기존의 배열 길이 보다 벗어나서 생기는 에러같다고 생각했다. 이를 해결해보자!

  • GPT 코드
class Solution {
    public int solution(int n, int m, int[] section) {
        int answer = 0;
        boolean[] tmp = new boolean[n];
        
        // Initialize the array to true
        for (int i = 0; i < n; i++) {
            tmp[i] = true;
        }
        
        // Mark sections as false
        for (int s = 0; s < section.length; s++) {
            int f = section[s];
            tmp[f - 1] = false;
        }
        
        // Process the array and count the number of operations needed
        for (int i = 0; i < n; i++) {
            if (!tmp[i]) {
                for (int j = i; j < Math.min(i + m, n); j++) {
                    tmp[j] = true;
                }
                answer++;
            }
        }
        
        return answer;
    }
}
  • 코드 변경 사항
    - 불필요한 변수 f를 제거
    - tmp가 원시 타입 boolean 배열이므로, Boolean.TRUE와 Boolean.FALSE를 각각 true와 false로 대체
    - 내부 루프가 배열의 경계를 넘지 않도록 Math.min(i + m, n)을 사용
    Math.min 함수를 써서 i+m, n 중에 작은 수를 선택했다. 이렇게 하면 i+m이 n보다 클 경우 n을 선택하게 되므로 배열의 범위를 벗어날 일이 없다.

  • 다른 사람의 풀이
class Solution {
    public int solution(int n, int m, int[] section) {
        int roller = section[0];
        int cnt = 1;
        for(int i = 1; i < section.length; i++) {
            if(roller + m - 1 < section[i]) {
                cnt++;
                roller = section[i];
            }
        }
        return cnt;
    }
}

roller라는 변수를 두어 section값을 넣어준 다음 roller+m-1 값이 그 다음 section값 보다 작으면 cnt를 증가한다. n영역을 위주로 생각을 했는데 section 영역만 고려해서 풀었다. 이렇게 풀면 따로 배열을 만들 필요도 없고 메모리 절감에도 훨씬 좋을 것 같다. 나도 언젠가 이렇게 풀고 싶다 ... 🥲

profile
유진진입니덩

0개의 댓글