File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments