class Solution {
public:
int minJumps(vector<int>& arr) {
int n = arr.size();
unordered_map<int,set<int>>hash;
for(int i = 0; i < n; i++)
{
hash[arr[i]].insert(i);
}
int res = 0;
vector<bool>visited(n,false);
queue<int>q;
q.push(0);
while(!q.empty())
{
int size = q.size();
for(int i = 0; i < size; i++)
{
int cur = q.front();
q.pop();
if(cur == arr.size()-1)
{
return res;
}
for(int j = -1; j <= 1; j += 2)
{
int next = cur + j;
if(next >= 0 && next < n && !visited[next])
{
q.push(next);
visited[next] = true;
}
}
set<int>::iterator it;
for(it = hash[arr[cur]].begin(); it != hash[arr[cur]].end(); it++)
{
int next = *it;
if(!visited[next])
{
q.push(next);
visited[next] = true;
}
}
hash.erase(arr[cur]); //从0经过当前层到这些值相同的点肯定是最短的
}
res++;
}
return res;
}
};