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++해준다.
#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;
}