-
Notifications
You must be signed in to change notification settings - Fork 21
/
JumpGame.js
83 lines (70 loc) · 1.44 KB
/
JumpGame.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
* Given an array of non-negative integers, you are initially positioned at the first index of the array.
*
* Each element in the array represents your maximum jump length at that position.
*
* Determine if you are able to reach the last index.
*
* For example:
* A = [2,3,1,1,4], return true.
*
* A = [3,2,1,0,4], return false.
*
* Accepted.
*/
/**
* @param {number[]} nums
* @return {boolean}
*/
let canJump = function (nums) {
if (nums == null || nums.length === 0) {
return false;
}
if (nums.length === 1) {
return true;
}
let maxLength = 0;
for (let i = 0; i < nums.length - 1; i++) {
maxLength--;
maxLength = Math.max(maxLength, nums[i]);
if (maxLength === 0) {
return false;
}
}
return maxLength > 0;
};
if (canJump(null) === false) {
console.log("pass")
} else {
console.error("failed")
}
if (canJump([]) === false) {
console.log("pass")
} else {
console.error("failed")
}
if (canJump([1])) {
console.log("pass")
} else {
console.error("failed")
}
if (canJump([0])) {
console.log("pass")
} else {
console.error("failed")
}
if (canJump([2, 3, 1, 1, 4])) {
console.log("pass")
} else {
console.error("failed")
}
if (canJump([3, 2, 1, 0, 4]) === false) {
console.log("pass")
} else {
console.error("failed")
}
if (canJump([4, 0, 0, 0])) {
console.log("pass")
} else {
console.error("failed")
}