File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -43,3 +43,41 @@ var minJumps = function (arr) {
43
43
}
44
44
return - 1
45
45
}
46
+
47
+ // another
48
+
49
+ /**
50
+ * @param {number[] } arr
51
+ * @return {number }
52
+ */
53
+ const minJumps = function ( arr ) {
54
+ if ( arr . length === 1 ) return 0
55
+ const n = arr . length
56
+ const indexMap = new Map ( )
57
+ for ( let i = n - 1 ; i >= 0 ; i -- ) {
58
+ if ( ! indexMap . has ( arr [ i ] ) ) {
59
+ indexMap . set ( arr [ i ] , [ ] )
60
+ }
61
+ indexMap . get ( arr [ i ] ) . push ( i )
62
+ }
63
+ let distance = 0
64
+ const queue = [ 0 ]
65
+ const visited = new Set ( )
66
+ visited . add ( 0 )
67
+ while ( queue . length ) {
68
+ const len = queue . length
69
+ for ( let i = 0 ; i < len ; i ++ ) {
70
+ const cur = queue . shift ( )
71
+ visited . add ( cur )
72
+ if ( cur === n - 1 ) return distance
73
+ if ( cur + 1 < n && ! visited . has ( cur + 1 ) ) queue . push ( cur + 1 )
74
+ if ( cur - 1 >= 0 && ! visited . has ( cur - 1 ) ) queue . push ( cur - 1 )
75
+ for ( let next of indexMap . get ( arr [ cur ] ) ) {
76
+ if ( ! visited . has ( next ) ) queue . push ( next )
77
+ }
78
+ indexMap . set ( arr [ cur ] , [ ] )
79
+ }
80
+ distance ++
81
+ }
82
+ return - 1
83
+ }
You can’t perform that action at this time.
0 commit comments