【leetcode刷题笔记】Jump Game II
2014-07-21 16:48
387 查看
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 =
The minimum number of jumps to reach the last index is
题解:跟Jump Game十分相像,把原来的boolean数组改成int型数组,用来记录到达i时候最小的步骤数目,遍历j(j<i),考察从j跳到i需要的步骤数目是否小于当前的reach[i],如果小于,就更新reach[i]。最终返回reach[A.length-1]即可。
代码如下:
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
1step from index 0 to 1, then
3steps to the last index.)
题解:跟Jump Game十分相像,把原来的boolean数组改成int型数组,用来记录到达i时候最小的步骤数目,遍历j(j<i),考察从j跳到i需要的步骤数目是否小于当前的reach[i],如果小于,就更新reach[i]。最终返回reach[A.length-1]即可。
代码如下:
public class Solution { public int jump(int[] A) { if(A == null || A.length == 0) return 0; int[] reach = new int[A.length]; Arrays.fill(reach, Integer.MAX_VALUE); reach[0] = 0; for(int i = 1;i < A.length;i++){ for(int j = 0;j < i;j++){ if(reach[j] != Integer.MAX_VALUE && j+A[j]>=i){ reach[i] = Math.min(reach[i], reach[j]+1); break; } } } return reach[A.length-1]; } }
相关文章推荐
- LeetCode刷题笔记(贪心):jump-game-ii
- LeetCode 笔记系列13 Jump Game II [去掉不必要的计算]
- leetcode笔记:Jump Game II
- LeetCode Online Judge 题目C# 练习 - Jump Game II
- [leetcode]Jump Game II
- [Leetcode 100] 130 Jump Game II
- LeetCode_Jump Game II
- LeetCode - Jump Game II
- LeetCode题目 Jump Game II
- LeetCode-Jump Game II
- [leetcode] Jump Game II
- leetcode - Jump Game II
- LeetCode Jump Game II
- [LeetCode] Jump Game II
- [leetcode]Jump Game II
- leetcode: Jump Game II
- LeetCode: Jump Game II
- [Leetcode] Jump Game II
- leetcode Jump Game II
- leetcode–jump game II