[leetcode-45]Jump Game II(c)
2015-08-02 15:59
441 查看
问题描述:
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.)
分析:该题是典型的DP问题,但是如果直接用DP算法,如代码1会超时,这里面有个trick就是,当上一次通过DP已经计算到的结尾,记录下来,当继续遍历的时候就从上次遍历的结尾处开始,因为,即使重复遍历,其结果也只会大于等于前者。所以不如直接跳过。另外,最后一个节点,一点被设置就立即返回。不必再遍历了。
代码1:TLE
AC代码如下:8ms
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.)
分析:该题是典型的DP问题,但是如果直接用DP算法,如代码1会超时,这里面有个trick就是,当上一次通过DP已经计算到的结尾,记录下来,当继续遍历的时候就从上次遍历的结尾处开始,因为,即使重复遍历,其结果也只会大于等于前者。所以不如直接跳过。另外,最后一个节点,一点被设置就立即返回。不必再遍历了。
代码1:TLE
[code]int jump(int *nums,int numsSize){ int i,j; int *steps = (int *)malloc(sizeof(int)*numsSize); for(i = 0;i<numsSize;i++) steps[i] = -1; steps[0] = 0; for(i = 0;i<numsSize;i++){ int val = nums[i]; for(j = i+1;j<=i+val&&j<numsSize;j++){ if(steps[j]==-1||steps[j]>steps[i]+1) steps[j] = steps[i]+1; } } return steps[numsSize-1]; }
AC代码如下:8ms
[code]int jump(int *nums,int numsSize){ int i,j; int *steps = (int *)malloc(sizeof(int)*numsSize); for(i = 0;i<numsSize;i++) steps[i] = -1; steps[0] = 0; int endIndex = 1; for(i = 0;i<numsSize;i++){ int val = nums[i]; for(j = endIndex;j<=i+val&&j<numsSize;j++){ if(steps[j]==-1||steps[j]>steps[i]+1) steps[j] = steps[i]+1; if(j==numsSize-1) return steps[j]; } endIndex = i+val+1; } return steps[numsSize-1]; }
相关文章推荐
- vector用法
- STL中的set容器的一点总结
- 有关collection中的一些数据结构
- uva12661 Dijkstra
- storyboard之 prepareForSegue:sender:
- leetcode 242: Valid Anagram
- android NumberPicker 数组越界的坑
- 【Angular JS】网站使用社会化评论插件,以及过程中碰到的坑
- 九度oj 1446
- ULN2003的简单使用
- Android Studio安装与gradle的关系
- 开放寻址法
- Java学习笔记(2015.7.27~7.31)
- uva 12300
- [深入理解Android卷一全文-第五章]深入理解常见类
- POJ 1862 Stripies(优先队列)
- Android UI 关于Android计量单位dip dp sp px 你所需要知道的一切
- Git
- [python]解析python打印出来的数组
- iOS基础-UIKit框架-手势处理