File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[] } arr
3
+ * @return {number }
4
+ */
5
+ var minJumps = function ( arr ) {
6
+ const dp = [ ] ;
7
+ dp [ arr . length - 1 ] = 0 ;
8
+
9
+ const map = { } ;
10
+ for ( let i = 0 ; i < arr . length ; i ++ ) {
11
+ map [ arr [ i ] ] = map [ arr [ i ] ] || [ ] ;
12
+ map [ arr [ i ] ] . push ( i ) ;
13
+ }
14
+
15
+ const queue = [ arr . length - 1 ] ;
16
+ while ( queue . length ) {
17
+ const i = queue . shift ( ) ;
18
+ if ( i === 0 ) {
19
+ return dp [ 0 ] ;
20
+ }
21
+
22
+ if ( i + 1 < arr . length && dp [ i + 1 ] === undefined ) {
23
+ dp [ i + 1 ] = dp [ i ] + 1 ;
24
+ queue . push ( i + 1 ) ;
25
+ }
26
+ if ( i - 1 >= 0 && dp [ i - 1 ] === undefined ) {
27
+ dp [ i - 1 ] = dp [ i ] + 1 ;
28
+ queue . push ( i - 1 ) ;
29
+ }
30
+ for ( const n of map [ arr [ i ] ] ) {
31
+ if ( n !== i && dp [ n ] === undefined ) {
32
+ dp [ n ] = dp [ i ] + 1 ;
33
+ queue . push ( n ) ;
34
+ }
35
+ }
36
+ }
37
+
38
+ return 0 ;
39
+ } ;
You can’t perform that action at this time.
0 commit comments