Skip to content

Commit a15307e

Browse files
authored
Create jump-game-iv.cpp
1 parent fa05b46 commit a15307e

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

C++/jump-game-iv.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int minJumps(vector<int>& arr) {
7+
unordered_map<int, vector<int>> groups;
8+
for (int i = 0; i < arr.size(); ++i) {
9+
groups[arr[i]].emplace_back(i);
10+
}
11+
int result = 0;
12+
queue<pair<int, int>> q({{0, 0}});
13+
unordered_set<int> lookup = {0};
14+
while (!q.empty()) {
15+
const auto [pos, step] = q.front(); q.pop();
16+
if (pos == arr.size() - 1) {
17+
result = step;
18+
break;
19+
}
20+
unordered_set<int> neighbors(groups[arr[pos]].cbegin(),
21+
groups[arr[pos]].cend());
22+
groups[arr[pos]].clear();
23+
neighbors.emplace(pos - 1), neighbors.emplace(pos + 1);
24+
for (const auto& p : neighbors) {
25+
if (0 <= p && p < arr.size() && !lookup.count(p)) {
26+
lookup.emplace(p);
27+
q.emplace(p, step + 1);
28+
}
29+
}
30+
}
31+
return result;
32+
}
33+
};

0 commit comments

Comments
 (0)