-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path818.race-car.java
More file actions
49 lines (42 loc) · 1.4 KB
/
818.race-car.java
File metadata and controls
49 lines (42 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
* @lc app=leetcode id=818 lang=java
*
* [818] Race Car
*/
// @lc code=start
class Solution {
public int racecar(int target) {
Queue<int[]> queue = new LinkedList<>();
//initialize with postion 0 with speed 1
queue.offer(new int[]{0, 1});
//initialize the visited set with postion 0 with speed 1
Set<String> visited = new HashSet<>();
visited.add("0-1");
int step = 0;
while (!queue.isEmpty()) {
for (int i = queue.size(); i > 0; i--) {
int[] curr = queue.poll();
if (curr[0] == target) {
return step;
}
//A
int[] nextA = new int[]{curr[0] + curr[1], curr[1] << 1};
String keyA = nextA[0] + "-" + nextA[1];
if (!visited.contains(keyA) && nextA[0] > 0 && nextA[0] < (target << 1)) {
queue.offer(nextA);
visited.add(keyA);
}
//R
int[] nextR = new int[]{curr[0], curr[1] > 0 ? -1 : 1};
String keyR = nextR[0] + "-" + nextR[1];
if (!visited.contains(keyR) && nextR[0] > 0 && nextR[0] < (target << 1)) {
queue.offer(nextR);
visited.add(keyR);
}
}
step++;
}
return -1;
}
}
// @lc code=end