File tree Expand file tree Collapse file tree 1 file changed +72
-0
lines changed Expand file tree Collapse file tree 1 file changed +72
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {number[] } arr
3+ * @return {number }
4+ */
5+ let minJumps = function ( arr ) {
6+ let n = arr . length
7+ if ( n === 1 ) {
8+ return 0
9+ }
10+
11+ // 连续出现超过两次的数字就抛弃掉
12+ let newArr = [ ]
13+ let sameCount = 0
14+ for ( let i = 0 ; i < arr . length ; i ++ ) {
15+ if ( arr [ i ] === arr [ i - 1 ] ) {
16+ sameCount += 1
17+ if ( sameCount >= 2 ) {
18+ continue
19+ } else {
20+ newArr . push ( arr [ i ] )
21+ }
22+ } else {
23+ newArr . push ( arr [ i ] )
24+ sameCount = 0
25+ }
26+ }
27+ arr = newArr
28+ n = arr . length
29+ // 遍历一遍 记录每个数字出现的下标位置
30+ let indexesMap = new Map ( )
31+ for ( let i = 0 ; i < n ; i ++ ) {
32+ let val = arr [ i ]
33+ let indexes = indexesMap . get ( val )
34+ if ( ! indexes ) {
35+ indexesMap . set ( val , [ i ] )
36+ } else {
37+ indexes . push ( i )
38+ }
39+ }
40+
41+ let visited = [ ]
42+ let count = 0
43+ let queue = [ 0 ]
44+ while ( queue . length ) {
45+ count ++
46+ let len = queue . length
47+ for ( let i = 0 ; i < len ; i ++ ) {
48+ let index = queue . shift ( )
49+ // 找到了 由于bfs的特性 此时用的跳跃次数一定是最少的
50+ if ( index === n - 1 ) {
51+ return count - 1
52+ }
53+
54+ // 没找到 继续把可以跳的几个位置都放入队列中
55+ let val = arr [ index ]
56+ let left = index - 1
57+ let right = index + 1
58+ let sameIndexes = indexesMap . get ( val )
59+
60+ if ( left >= 0 && ! visited [ left ] ) queue . push ( left )
61+ if ( right < n && ! visited [ right ] ) queue . push ( right )
62+ for ( let sameIndex of sameIndexes ) {
63+ if ( sameIndex !== index && ! visited [ sameIndex ] ) {
64+ queue . push ( sameIndex )
65+ }
66+ }
67+
68+ visited [ index ] = true
69+ }
70+ }
71+ return n
72+ }
You can’t perform that action at this time.
0 commit comments