코테/프로그래머스

[프로그래머스/Lv. 1] 덧칠하기

imname1am 2023. 4. 4. 22:22
반응형

🔺 문제

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

🔺 코드

- 틀림

import java.util.*;

class Solution {
    public int solution(int n, int m, int[] section) {
        
        int answer = 0;
        Arrays.sort(section);
        
        for(int i = 0 ; i < section.length ; i++) {
            if((section[i] + m - 1) < section[section.length - 1]) {
                answer++;
            } else {
            	answer++;
                break;
            }
        }
        
        return answer;
    }
}

section 배열을 오름차순으로 정렬하고,

롤러가 칠한 벽이 section에서 제일 큰 값(=마지막 원소 값)보다 작으면 반복문을 다시 돌게 하려고 했다...

그런데...!!!

 

 

 

 

- 정답

 

프로그래머스 lv2 덧칠하기

덧칠하기이미 칠해진 곳은 덧칠해도 상관없음다만 최소로 칠하는 덧칠 횟수 찾기처음에는 덧칠해야하는 곳중에서 시작한다.시작점 + 롤러너비를 max 값으로 잡아서 그 다음에 덧칠해야하는 빈

velog.io

class Solution {
    public int solution(int n, int m, int[] section) {
        int answer = 0;
        int max = 0;
        
        for(int i = 0 ; i < section.length ; i++) {
            if(section[i] < max) {
                continue;
            }
            
            answer++;
            max = section[i] + m;   // 시작점 + 롤러 너비
        }
        
        return answer;
    }
}

다른 분 코드 보고 해결...

어찌 이리 머리가 안 돌아가는가..

 


🔺 다른 풀이들

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

- 풀이1)

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;
    }
}

초기 작성한 코드에서 어디가 틀렸는지 알았다... if문에서 틀린 것이었,,,,,,ㅠ

 

 

- 풀이2)

class Solution {
    public int solution(int n, int m, int[] section) {
        int maxPainted = 0, cntPaint = 0;
        for (int point : section) {
            if (maxPainted <= point) {
                maxPainted = point + m;
                cntPaint++;
            }
        }
        return cntPaint;
    }
}

if문이 약간 다른!


💬 느낀 점

수도코드를 꼭 작성하고... 구현해야겠다.

그냥 막 하려니까 안 되는...

반응형