1
+ // Runtime: 8 ms (Top 86.11%) | Memory: 41.5 MB (Top 82.95%)
1
2
class Solution {
2
3
public int racecar (int target ) {
3
4
Queue <int []> queue = new LinkedList <>();
4
5
queue .add (new int []{0 , 1 , 0 });
5
6
Set <String > visited = new HashSet <>();
6
-
7
+
7
8
while (!queue .isEmpty ()){
8
9
int [] item = queue .poll ();
9
10
int currPos = item [0 ];
@@ -17,7 +18,7 @@ public int racecar(int target) {
17
18
int nextPos = currPos + currSpeed ;
18
19
int nextSpeed = currSpeed * 2 ;
19
20
String posSpeed = new StringBuilder ().append (nextPos ).append ("," ).append (nextSpeed ).toString ();
20
-
21
+
21
22
// If the particular state (position & speed) is not encountered earlier then we explore that state
22
23
// And we also check if the nextPos is not beyond twice the size of target, then there is no point in exploring that route
23
24
if (!visited .contains (posSpeed ) && Math .abs (nextPos ) < 2 * target ){
@@ -26,11 +27,11 @@ public int racecar(int target) {
26
27
}
27
28
28
29
// Choosing R
29
- // We go in reverse only when we are moving away from the target in the positive or in the negative direction
30
+ // We go in reverse only when we are moving away from the target in the positive or in the negative direction
30
31
if ((currPos + currSpeed > target && currSpeed > 0 ) || (currPos + currSpeed < target && currSpeed < 0 )) {
31
32
nextSpeed = currSpeed > 0 ? -1 : 1 ;
32
33
posSpeed = new StringBuilder ().append (currPos ).append ("," ).append (nextSpeed ).toString ();
33
-
34
+
34
35
if (!visited .contains (posSpeed ) && Math .abs (currPos ) < 2 * target ){
35
36
visited .add (posSpeed );
36
37
queue .add (new int []{currPos , nextSpeed , distance + 1 });
@@ -39,4 +40,4 @@ public int racecar(int target) {
39
40
}
40
41
return -1 ;
41
42
}
42
- }
43
+ }
0 commit comments