



나의 풀이
class Solution {
public int solution(int n, int m, int[] section) {
int answer = 1; // 1
int start = section[0]; // 2
for (int i = 1; i < section.length; i++) { // 3
if (section[i] - start > m - 1) { // 4
answer++;
start = section[i];
}
}
return answer;
}
}
과정
- 제한 사항에 section의 길이는 1보다 같거나 크니 무조건 1번 이상의 롤러질을 하니까 시작값을 1로 둔다
- 시작점 start를 section의 0번째 배열로 둔다
- start를 0번째로 뒀으니 1부터 시작해서 section의 크기까지 도는 반복문을 선언
- 만약 section[i]에서 start를 뺀 값이 m - 1보다 크다면(1개의 벽은 포함이 되니 -1을 해준다) answer++를 해주고, start를 section[i]로 지정
다른 사람 풀이
import java.util.*;
class Solution {
public int solution(int n, int m, int[] section) {
int[] arr = new int[n+1];
Arrays.fill(arr, 1);
for(int i = 0; i < section.length; i++)
arr[section[i]] = 0;
int count = 0;
int i = 0;
while(true) {
int idx = section[i++];
if(arr[idx] == 0) {
count++;
for(int j = idx; j < idx + m; j++) {
if(j > n)
break;
arr[j] = 1;
}
}
if(idx == section[section.length-1])
break;
}
return count;
}
}
- Arrays.fill(arr, 1) : 배열의 모든 값을 지정한 값으로 초기화하는 메서드