var canJump = function (nums) {
let max = 0;
for (let i = 0; i < nums.length; i++) {
max = Math.max(i + nums[i], max);
console.log('max: ', max);
console.log('i: ', i);
if (max === i) { // Discussion의 도움을 받은 부분
console.log('걸렸냐?');
break;
}
}
if (max >= nums.length - 1) return true;
else return false;
};
스스로 완전히 해결하지 못하고, Discussion의 도움을 받았다. 코드를 요약하자면, max(i+nums[i]
가 nums.length - 1
보다 커지는 경우를 찾을 때 true
를 반환, 그렇지 않을 경우에는 false
를 반환해야 한다.
max === i
의 경우 example2의 case처럼 nums = [3,2,1,0,4]
이렇게 nums
가 주어졌을 때 3번째 인덱스인 0
에서 max === i
조건을 만족하게 된다. 따라서 example2의 설명에도 나와있듯이
You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
더 반복해도 의미가 없기 때문에, break을 통해 loop을 탈출한다.
수정, 지적을 환영합니다. 스스로 풀지 못하고 Discussion의 도움을 받은 문제이기 때문에 오류가 있을 수 있습니다.
https://leetcode.com/problems/jump-game/
https://github.com/tTab1204/LeetCode/tree/main/%EC%A3%BC%EC%98%81