[Programmers / Level1] 161989.덧칠하기(Java)

이하얀·2024년 7월 18일
0

🕊️ 프로그래머스

목록 보기
14/43

💡 Info




입출력 조건




입출력 예시






문제 이해


  • 주어진 조건을 벗어나지 않는 상황에서 롤러의 최소 사용 횟수를 반환하는 문제


알고리즘


풀이 시간 : 12분

  • 입력
    • 페인트칠 시작점 startP, 페인트칠 끝점 endP, 선언하기
  • 계산
    • for문으로 조건을 벗어나지 않는 한 반복
    • start <= i <= end를 만족한다면(진행중) -> continue
    • 그렇지 않다면(완료) -> 해당 값을 answer에 증가
  • 출력
    • answer 반환
import java.util.*;

class Solution {
    public int solution(int n, int m, int[] section) {
        int startP = section[0];
        int endP = section[0] + (m-1);        
        int answer = 0;
        
        for(int i=0; i<section.length; i++){
            if(i>=startP && i<= endP) continue;
            else {
                startP = i;
                endP = i + (m-1);
                answer++;
            }
        }
        return answer;
    }
}


오답체크


  • 첫번째 테스트의 경우 통과하지 못하는 문제 발생
    • m과 n은 1부터 시작해야하고 마찬가지로, for문의 범위도 1부터 section.length까지를 포함하는 범위로 수정해야 함.
//before
int answer = 0;
        
for(int i=0; i<section.length; i++){
//after
int answer = 1;
        
for(int i=1; i<=section.length; i++){

  • 정확성 테스트 미통과 문제
    • startP를 제거하고, endP만 가지고 연산하도록 수정
    • 또한 초기값을 0으로 재설정
//before
int answer = 1;
        
for(int i=1; i<=section.length; i++){
//after
int answer = 0;
int endP = 0;
        
for(int i=0; i<section.length; i++){
	if(section[i] > endP){
		endP = section[i] + m - 1;
        answer++;
    }
}


최종 풀이


풀이 시간 : 35분(첫 풀이 시간 포함)

  • 입력
    • 페인트칠 끝점 endP 선언하기
  • 계산
    • for문으로 조건을 벗어나지 않는 한 반복
    • section[i] > endP를 만족한다면(완료) -> 해당 값을 answer에 증가
  • 출력
    • answer 반환
import java.util.*;

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


결과






profile
언젠가 내 코드로 세상에 기여할 수 있도록, BE 개발 기록 노트☘️

0개의 댓글