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

YH J·2023년 4월 25일
0

프로그래머스

목록 보기
77/168

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/161989

내 풀이

m은 1인경우와 0인 경우는 따로 처리해둔다.
answer을 1로 초기화 해둔다.
while이나 for문을 돌리면서 section[0]의 위치에서 한 번 칠하였을 때의 범위를 벗어나는지 체크하여 벗어나지 않으면 다음 인덱스로 가고
벗어나면 num을 갱신해준 뒤 칠하는 횟수를 ++ 해준다.

내 코드

#include <string>
#include <vector>

using namespace std;

int solution(int n, int m, vector<int> section) {
    int answer = 1;
    if(m == 1)
        return section.size();
    else if(section.size() == 0)
        return 0;
    int index = 0;
    int num = section[index];
    while(index < section.size())
    {
        if(section[index] > num + m - 1)
        {
            num = section[index];
            answer++;
        }
        else
        {
            index++;
        }
    }
    
    return answer;
}

다른 사람의 풀이

#include <string>
#include <vector>

using namespace std;

int solution(int n, int m, vector<int> section) {
    int answer = 1;

    int pivot = section[0];
    for(const auto v : section)
    {
        if(v < pivot + m)
        {
            continue;
        }
        else
        {
            pivot = v;
            answer++;
        }
    }

    return answer;
}

다른 사람의 풀이 해석

똑같이 범위를 벗어나지 않으면 continue하고 벗어나면 pivot을 갱신하고 answer++해준다.

다른 사람의 풀이2

#include <string>
#include <vector>

using namespace std;

int solution(int n, int m, vector<int> section) {
    int answer = 0;
    int done = 0;
    for (int position : section) {
        if (position > done) {
            done = position + m - 1;
            answer++;
        }
    }
    return answer;
}
profile
게임 개발자 지망생

0개의 댓글