Skip to content

Commit 370a356

Browse files
committed
045
1 parent 9bbcbd6 commit 370a356

File tree

1 file changed

+16
-26
lines changed

1 file changed

+16
-26
lines changed

045/main.js

Lines changed: 16 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,21 @@
22
* @param {number[]} nums
33
* @return {number}
44
*/
5-
var jump = function (nums) {
6-
const steps = {}
7-
let reach = 0
8-
steps[0] = 0
9-
10-
for (let index = 0; index < nums.length; index++) {
11-
const item = nums[index]
12-
const step = steps[index]
13-
const start = reach + 1
14-
const end = Math.min(nums.length, index + item + 1)
15-
for (let i = start; i < end; i++) {
16-
steps[i] = step + 1
17-
}
18-
reach = Math.max(reach, index + item)
19-
if (end >= nums.length) {
20-
break
5+
var jump = function(nums) {
6+
if (nums.length <= 1) return 0
7+
let step = 0
8+
let curMax = 0
9+
let nextMax = 0
10+
let i = 0
11+
while (i < nums.length) {
12+
curMax = nextMax
13+
while (i < nums.length && i <= curMax) {
14+
nextMax = Math.max(nextMax, i + nums[i])
15+
i++
2116
}
17+
step++
18+
curMax = nextMax
19+
if (curMax >= nums.length - 1) return step
2220
}
23-
24-
return steps[nums.length - 1]
25-
}
26-
27-
if (process.env.LZS) {
28-
// local test
29-
console.log(jump([3, 1, 2, 4]))
30-
console.log(jump([3, 1, 2, 5, 4]))
31-
console.log(jump([3]))
32-
}
21+
return step
22+
};

0 commit comments

Comments
 (0)