leetcode 45.Jump GameII
来源:互联网 发布:淘宝手机端买家秀 编辑:程序博客网 时间:2024/06/08 15:16
题目描述:
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.)
分析:此题没有考虑无法到达终点的情况。思路是分别比较直接从该位置跳跃出最大步数和跳跃一步到下一个位置从该位置继续跳跃哪一个跳跃长度长,贪最长的。
AC代码(来自九章算法Java版)
public class Solution { public int jump(int[] nums) { if(nums==null||nums.length==0) return 0; int start=0,end=0,jumps=0; while(end<nums.length-1){ jumps++; int len=end; for(int i=start;i<=end;i++){ if(nums[i]+i>len){ len=nums[i]+i; } } start=end+1; end=len; } return jumps; }}
可以变形一道题目,题目来自2017搜狐校招真题
[编程题] 袋鼠过河
时间限制:1秒
空间限制:32768K
一只袋鼠要从河这边跳到河对岸,河很宽,但是河中间打了很多桩子,每隔一米就有一个,每个桩子上都有一个弹簧,袋鼠跳到弹簧上就可以跳的更远。每个弹簧力量不同,用一个数字代表它的力量,如果弹簧力量为5,就代表袋鼠下一跳最多能够跳5米,如果为0,就会陷进去无法继续跳跃。河流一共N米宽,袋鼠初始位置就在第一个弹簧上面,要跳到最后一个弹簧之后就算过河了,给定每个弹簧的力量,求袋鼠最少需要多少跳能够到达对岸。如果无法到达输出-1
输入描述:
输入分两行,第一行是数组长度N (1 ≤ N ≤ 10000),第二行是每一项的值,用空格分隔。
输出描述:
输出最少的跳数,无法到达输出-1
输入例子1:
5
2 0 1 1 1
输出例子1:
4
分析:
结题思路同Jump Game,但是要考虑未能抵达的情况,也好判断,就是当步数大于数组数说明未能抵达。
AC代码(c++版)
#include <iostream>#include <string>using namespace std;int jump(int nums[], int n) { if (n == 0) return 0; int start = 0, end = 0, jumps = 0; while (jumps<=n&&end<=n - 1){ ++jumps; int len = end; for (int i = start; i <= end; i++){ if (nums[i] + i>len){ len = nums[i] + i; } } start = end + 1; end = len; } if (jumps > n) jumps = -1; return jumps;}int main(){ int n; cin >>n; int *array=new int[n]; for (int i = 0; i < n; i++){ cin >> array[i]; } cout << jump(array, n); return 0;}
- leetcode 45.Jump GameII
- LeetCode Jump Game && Jump GameII
- Jump gameII
- Leetcode——45Jump GameII
- LeetCode Week7: Jump Game&Jump GameII、Patching Arrays
- 贪心法、动态规划——jump-game,jump-gameII
- LeetCode --- 45. Jump Game II
- LeetCode 45.Jump Game II
- [Leetcode] 45. Jump Game II
- [leetcode] 45.Jump Game II
- [leetcode] 45.Jump Game II
- leetcode 45. Jump Game II
- LeetCode 45. Jump Game II
- LeetCode 45. Jump Game II
- leetcode.45. Jump Game II
- leetcode 45. Jump Game II
- leetcode 45. Jump Game II
- [LeetCode] 45. Jump Game II
- Bag of words模型简介
- 【PAT B1019/A1069】数字黑洞
- 关于滴滴出行产品类实习三个面试
- WIN2008加入域提示“找不到网络路径”
- String类
- leetcode 45.Jump GameII
- python write和writelines的区别
- python爬虫xpath针对json代码的分析方法
- 仿糖护士曲线图写的一个CurveChartView
- JS延迟执行下一条语句/action页面跳转
- oracle练习题
- ELK(八)ElasticSearch2.X版本优化
- C#中获取当前时间:System.DateTime.Now.ToString()用法
- javascript获取style(兼容ie和w3c)