for(변수 생성 : 배열 이름){
...
}
배열에 있는 데이터 하나 하나 읽고 배열이 끝나면 for문 탈출
break는 for문 즉시 탈출
continue는 이번 반복 중단, 다음 데이터 처리
벽이 5일때 1,2,3,4,5 라면 1이 1을 이미 칠한 후인지, 1을 칠하기 전인지 위치가 헷깔렸음
그래서 <, >, <=, >= 부호도 같이 헷깔렸음
class Solution {
public int solution(int n, int m, int[] section) {
int answer = 0;
int i = section[0];
int j = 0;
//while문 조건은 현재 위치가 전체 벽길이보다 작을 때
while(i <= n){
i += m;
answer++; // 벽 칠해놓고 칠한 수 증가++
while(j < section.length){ //section 배열 훝기
if(i <= section[j]) break; //배열 데이터보다 현재위치가 크면 거기서부터 시작
else j++;
}
if (j >= section.length) break; // section 다읽으면 끝내기
}
return answer;
}
}
알고리즘이 빈약할 때 나오는 결과..
결과만 나오도록 짜는 습관 고치기!!!!
class Solution {
public int solution(int n, int m, int[] section) {
int answer = 0;
int fromTo = section[0];
int i = -1;
answer++;
while(i < section.length){ //while문 조건은 section 배열 끝날때까지
i++;
if(i == section.length || fromTo + m > section[i]) continue;
// section 배열 끝나거나 현재위치보다 section 데이터가 클때까지 배열 순회
// section 배열 끝나면 continue 때문에 while 조건으로 감
fromTo = section[i]; // 새로운 위치는 새 section 데이터 자리
answer++;
}
return answer;
}
}
-> 멘탈 탈탈 털렸다. Level1의 이 짧고 간단한 코드 하나 못짜고 있는 나에게 대실망함
3시간 들여다봐도, 몇번이나 다 지우고 다시 처음부터 시작해보려고 해도 정답이 안나와서 답답했다.
다른사람 코드 보고 빠르게 익히기 vs 끙끙대면서 결국 풀어내기 둘중 고민하다가 결국 시간을 아끼기 위해 다른사람 코드 참고ㅠ
오늘은 기부니 꿀꿀하구만
class Solution {
public int solution(int n, int m, int[] section) {
int answer = 0;
int fromTo = section[0];
answer++;
for(int nowSec : section){
if(fromTo + m > nowSec) continue;
fromTo = nowSec;
answer++;
}
return answer;
}
}