力扣练习题目——Jump Game IV

给定一个整数数组,从第一个索引开始,你可以按i+1、i-1或者到值相等的其他索引j跳跃。目标是到达数组的最后一个索引,返回达到目标所需的最小步数。文章提供了一个使用BFS并借助字典存储值与索引关系的Python解决方案。

Jump Game IV

Given an array of integers arr, you are initially positioned at the first index of the array.

In one step you can jump from index i to index:

  • i + 1 where: i + 1 < arr.length.
  • i - 1 where: i - 1 >= 0.
  • j where: arr[i] == arr[j] and i != j.

Return the minimum number of steps to reach the last index of the array.

Notice that you can not jump outside of the array at any time.

Example 1:

Input: arr = [100,-23,-23,404,100,23,23,23,3,404]
Output: 3
Explanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.

Example 2:

Input: arr = [7]
Output: 0
Explanation: Start index is the last index. You do not need to jump.

Example 3:

Input: arr = [7,6,9,6,9,6,9,7]
Output: 1
Explanation: You can jump directly from index 0 to index 7 which is last index of the array.

Constraints:

  • 1 <= arr.length <= 5 * 104
  • -10^8 <= arr[i] <= 10^8

题解

下次看到一维数组的最少步数寻路问题基本都用BFS

求解步骤

  • 建立一个num_dic,存储 值:下标集合 的映射关系,建立队列q。
  • 用BFS,每一步,判断当前的坐标cur_pos是否为arr.size()-1:
    • 如果是,返回当前的坐标
    • 否则,将cur_pos+1、cur_pos-1、num_dic[cur_pos]中的每一个坐标都加入q中。继续下一个
  • 注意要vis。

代码

MAX=5*10**4+5
class Solution:
    def minJumps(self, arr: List[int]) -> int:
        n=len(arr)
        min_step=[MAX for i in range(n)]
        num_dic={}
        for i in range(n):
            if arr[i] in num_dic:
                num_dic[arr[i]].append(i)
            else:
                num_dic[arr[i]]=[i]
        q=deque()
        q.append([0,0])
        vis=[False for i in range(n)]
        while len(q)>0:
            if q[0][0]==n-1:
                return q[0][1]
            cur_pos,cur_ct=q.popleft()
            vis[cur_pos]=True
            if cur_pos+1<n and vis[cur_pos+1]==False:
                q.append([cur_pos+1,cur_ct+1])
            if cur_pos-1>=0 and vis[cur_pos-1]==False:
                q.append([cur_pos-1,cur_ct+1])
            for j in num_dic[arr[cur_pos]]:
                if vis[j]==False:
                    q.append([j,cur_ct+1])
            num_dic[arr[cur_pos]]=[]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值