Skip to content

Commit 50f6b96

Browse files
authored
Update 1345-jump-game-iv.js
1 parent a104f0c commit 50f6b96

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

1345-jump-game-iv.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,41 @@ var minJumps = function (arr) {
4343
}
4444
return -1
4545
}
46+
47+
// another
48+
49+
/**
50+
* @param {number[]} arr
51+
* @return {number}
52+
*/
53+
const minJumps = function (arr) {
54+
if (arr.length === 1) return 0
55+
const n = arr.length
56+
const indexMap = new Map()
57+
for (let i = n - 1; i >= 0; i--) {
58+
if (!indexMap.has(arr[i])) {
59+
indexMap.set(arr[i], [])
60+
}
61+
indexMap.get(arr[i]).push(i)
62+
}
63+
let distance = 0
64+
const queue = [0]
65+
const visited = new Set()
66+
visited.add(0)
67+
while (queue.length) {
68+
const len = queue.length
69+
for(let i = 0; i < len; i++) {
70+
const cur = queue.shift()
71+
visited.add(cur)
72+
if(cur === n - 1) return distance
73+
if(cur + 1 < n && !visited.has(cur + 1)) queue.push(cur + 1)
74+
if(cur - 1 >= 0 && !visited.has(cur - 1)) queue.push(cur - 1)
75+
for(let next of indexMap.get(arr[cur])) {
76+
if(!visited.has(next)) queue.push(next)
77+
}
78+
indexMap.set(arr[cur], [])
79+
}
80+
distance++
81+
}
82+
return -1
83+
}

0 commit comments

Comments
 (0)