Skip to content

Commit d8f1bd0

Browse files
committed
Runtime: 8 ms (Top 86.11%) | Memory: 41.5 MB (Top 82.95%)
1 parent d74384c commit d8f1bd0

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

scripts/algorithms/R/Race Car/Race Car.java

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1+
// Runtime: 8 ms (Top 86.11%) | Memory: 41.5 MB (Top 82.95%)
12
class Solution {
23
public int racecar(int target) {
34
Queue<int[]> queue = new LinkedList<>();
45
queue.add(new int[]{0, 1, 0});
56
Set<String> visited = new HashSet<>();
6-
7+
78
while(!queue.isEmpty()){
89
int[] item = queue.poll();
910
int currPos = item[0];
@@ -17,7 +18,7 @@ public int racecar(int target) {
1718
int nextPos = currPos + currSpeed;
1819
int nextSpeed = currSpeed * 2;
1920
String posSpeed = new StringBuilder().append(nextPos).append(",").append(nextSpeed).toString();
20-
21+
2122
// If the particular state (position & speed) is not encountered earlier then we explore that state
2223
// And we also check if the nextPos is not beyond twice the size of target, then there is no point in exploring that route
2324
if(!visited.contains(posSpeed) && Math.abs(nextPos) < 2 * target){
@@ -26,11 +27,11 @@ public int racecar(int target) {
2627
}
2728

2829
// 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
3031
if((currPos + currSpeed > target && currSpeed > 0) || (currPos + currSpeed < target && currSpeed < 0)) {
3132
nextSpeed = currSpeed > 0 ? -1 : 1;
3233
posSpeed = new StringBuilder().append(currPos).append(",").append(nextSpeed).toString();
33-
34+
3435
if(!visited.contains(posSpeed) && Math.abs(currPos) < 2 * target){
3536
visited.add(posSpeed);
3637
queue.add(new int[]{currPos, nextSpeed, distance + 1});
@@ -39,4 +40,4 @@ public int racecar(int target) {
3940
}
4041
return -1;
4142
}
42-
}
43+
}

0 commit comments

Comments
 (0)