[LeetCode] 45. Jump Game II 解题思路

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

问题:给定一个数组,每个元素表示你站在该位置可以跳的最大距离。假设你站在第一个元素,求你可以跳到最后元素的最小跳跃次数。

题目简洁,解题却不容易。

数组中的元素值是代表一个范围区间,题目需要求的是最小跳跃次数,也就是每一次的跳跃覆盖的范围应该尽可能远,这是一个大致思路。

  • 假设 [ start, end ] 表示第 i 次跳跃才能到达的区间,nextEnd 代表在该区间中起跳的下一个最远元素,那么,[ end+1, nextEnd ] 表示第 i+1 次跳才能去到的范围区间。
  • 初始化 [start , end] 为 [0,0],重复执行上面操作,直到 [start, end] 覆盖到终点元素。由于 [start, end] 表示第 i  次跳跃才能到达的区间,所以 i 便是最小的跳跃次数。

在代码实现中, start  变量没有影响到程序的执行,加进去只是为了方便理解。

这个解题思路我没能想到,是参考了 LeetCode 论坛才理解到 : 10-lines C++ (16ms) / Python BFS Solutions with Explanations Single loop simple java solution

 1     int jump(vector<int>& nums) {
 2         
 3         int start = 0;
 4         int end = 0;
 5         
 6         int cnt = 0;
 7         
 8         int nextEnd = 0;
 9         
10         for (int i = 0 ; i < nums.size()-1; i++) {
11 
12             if (i > end) {
13                 return -1;
14             }
15             
16             nextEnd = max(nextEnd, i + nums[i]);
17             if (i == end) {
18                 start = i + 1;
19                 end = nextEnd;
20                 cnt++;
21             }
22         }
23         
24         return cnt;
25     }

 

一开始使用了 DP 解法,已经参照了 LeetCode 的另一个思路,不过时间复杂度都是 O(n*n),都超时。

转载于:https://www.cnblogs.com/TonyYPZhang/p/5084523.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值