forked from jyxia/LeetCode-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path45-jumpGameII.js
42 lines (38 loc) · 1.04 KB
/
45-jumpGameII.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* @param {number[]} nums
* @return {number}
*/
var jump = function(nums) {
var jumpTo = 0;
var lastReach = 0;
var jumps = 0;
for (var i = 0; i < nums.length && i <= jumpTo; i++) {
//when last jump can not reach i, increase the step by 1
if (i > lastReach) {
jumps++;
lastReach = jumpTo;
}
jumpTo = Math.max(jumpTo, nums[i] + i);
}
return lastReach >= nums.length - 1 ? jumps : 0;
};
// second solution, easy understanding. Nice solution. BFS
// [2,3,1,1,4] 2 -> 3, 1 -> 4
var jump = function(nums) {
var curr = 0;
var next = 0;
var jumps = 0;
var length = nums.length;
for (var i = 0; i < length;) {
if (curr >= length - 1) break;
// find the next (max jump to) of every element before (including) current element
// once the next is chosen, it is one step jump.
while (i <= curr) {
next = Math.max(i + nums[i], next);
i++;
}
jumps++;
curr = next;
}
return jumps;
};