topic
https://leetcode-cn.com/problems/jump-game-iv/solution/
You are given an array of integers arr, you start at the first element of the array (the subscript is 0).
At each step, you can jump from subscript i to subscript:
i + 1 satisfies: i + 1 <arr.length
i-1 satisfies: i-1> = 0
j satisfies: arr [i] == arr [j] and i! = j
please return to the last element of the array The minimum number of operations required at the subscript.
Note: You cannot jump outside the array at any time.
Example 1:
Input: arr = [100, -23, -23,404,100,23,23,23,3,404]
Output: 3
Explanation: Then you need to jump 3 times, the subscripts are 0-> 4-> 3-> 9 . Subscript 9 is the subscript of the last element of the array.
Example 2:
Input: arr = [7]
Output: 0
Explanation: It is at the last element at the beginning, so you don't need to jump.
Example 3:
Input: arr = [7,6,9,6,9,6,9,7]
Output: 1
Explanation: You can jump directly from subscript 0 to subscript 7, which is the last element of the array.
Example 4:
Input: arr = [6,1,9]
Output: 2
Example 5:
Input: arr = [11,22,7,7,7,7,7,7,7,22,13]
Output: 3
prompt:
1 <= arr.length <= 5 * 10^4
-10^8 <= arr[i] <= 10^8
Problem-solving ideas
- First use a dictionary to store array values and subscript lists
- For consecutive characters, such as "77 ... 77", only record the first and last, skip the middle, otherwise TLE
- The rest is the standard BFS process
Code
class Solution:
def minJumps(self, arr: List[int]) -> int:
g = defaultdict(list)
for i,a in enumerate(arr):
# - key optimization
# - skip continous value, such as '77...77', only keep first and last 7
if (i > 0) and (i < len(arr) - 1) and (a == arr[i-1] == arr[i+1]):
continue
g[a].append(i)
seen_set = set([0])
q = [(0,0)]
step = 0
while q:
p, step = q.pop(0)
# - check if touch the end
if p == len(arr) - 1:
return step
for k in [p-1, p+1] + g[arr[p]]:
if k in seen_set: continue
if 0 <= k <= len(arr)-1:
seen_set.add(k)
q.append((k, step+1))
return 0