@@ -35,40 +35,21 @@ You can assume that you can always reach the last index.
35
35
## Solution
36
36
37
37
``` typescript
38
- function jump(nums : number []): number { // NOSONAR
39
- let minJmp = new Array (nums .length )
40
- if (nums .length === 1 ) return 0
41
- let prevIndex = 0
42
- minJmp [prevIndex ] = 0
43
- while (prevIndex < nums .length - 1 ) {
44
- let nextMaxJmpTo = nums [prevIndex ] + prevIndex
45
- let prevIndexJmp = minJmp [prevIndex ]
46
-
47
- let farthestJumpVal = - 1
48
- let farthestJumpIndex = - 1
49
- for (let i = nextMaxJmpTo ; ; i -- ) {
50
- if (i >= nums .length ) {
51
- continue
52
- }
53
- if (i === nums .length - 1 ) {
54
- return prevIndexJmp + 1
55
- }
56
- if (minJmp [i ] != undefined ) {
57
- break
58
- }
59
- minJmp [i ] = prevIndexJmp + 1
60
- let curmaxTo = nums [i ] + i
61
- if (farthestJumpVal < curmaxTo ) {
62
- farthestJumpVal = curmaxTo
63
- farthestJumpIndex = i
64
- }
38
+ function jump(nums : number []): number {
39
+ let minJump = 0 ,
40
+ farthest = 0 ,
41
+ currentEnd = 0
42
+ for (let i = 0 ; i < nums .length - 1 ; i ++ ) {
43
+ farthest = Math .max (farthest , i + nums [i ])
44
+ // If we've reached the end of the current jump range
45
+ if (i === currentEnd ) {
46
+ minJump ++
47
+ currentEnd = farthest
48
+
49
+ if (currentEnd >= nums .length - 1 ) break
65
50
}
66
- if (farthestJumpIndex === - 1 ) {
67
- return - 1
68
- }
69
- prevIndex = farthestJumpIndex
70
51
}
71
- return minJmp [ nums . length - 1 ]
52
+ return minJump
72
53
}
73
54
74
55
export { jump }
0 commit comments