File tree 1 file changed +8
-7
lines changed
scripts/algorithms/R/Race Car
1 file changed +8
-7
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 3079 ms (Top 11.52%) | Memory: 74 MB (Top 23.64%)
2
+
1
3
var racecar = function ( target ) {
2
4
let queue = [ [ 0 , 1 , 0 ] ] ;
3
5
let visited = new Set ( [ '0,1' ] ) ;
4
-
6
+
5
7
while ( queue . length > 0 ) {
6
8
const [ pos , speed , distance ] = queue . shift ( ) ;
7
-
9
+
8
10
if ( pos === target ) return distance ;
9
-
11
+
10
12
const posA = pos + speed ;
11
13
const speedA = speed * 2 ;
12
14
const keyA = posA + ',' + speedA ;
13
-
15
+
14
16
const posR = pos ;
15
17
const speedR = speed > 0 ? - 1 : 1 ;
16
18
const keyR = posR + ',' + speedR ;
17
-
18
-
19
+
19
20
if ( ! visited . has ( keyA ) && posA >= 0 && posA <= 2 * target ) {
20
21
visited . add ( keyA ) ;
21
22
queue . push ( [ posA , speedA , distance + 1 ] ) ;
22
23
}
23
-
24
+
24
25
if ( ! visited . has ( keyR ) && posR >= 0 && posR <= 2 * target ) {
25
26
visited . add ( keyR ) ;
26
27
queue . push ( [ posR , speedR , distance + 1 ] ) ;
You can’t perform that action at this time.
0 commit comments