[LeetCode39]Jump Game II
2014-06-04 02:39
411 查看
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
from index 0 to 1, then
Analysis
Using greedy idea, every time get the max length. Details see the code. Matain a maximum scope
java
c++
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.)
Analysis
Using greedy idea, every time get the max length. Details see the code. Matain a maximum scope
java
public int jump(int[] A) { int n = A.length; if(n==0 ||n==1) return 0; int max=0; int start = 0; int njump = 0; while(start<n){ max = Math.max(max, A[start]+start); if(max>0) njump++; if(max>=n-1) return njump; int temp=0; for(int j = start+1;j<=max;j++){ if(A[j]+j>temp){ temp = A[j]+j; start = j; } } } return njump; }
c++
int jump(int A[], int n) { int start = 0; int end = 0; int count = 0; if(n==1) return 0; while(end<n){ int max = 0; count++; for(int i = start; i<=end;i++){ if(A[i]+i >= n-1){ return count; } if(A[i]+i > max){ max = A[i]+i; } } start = end+1; end = max; } }
相关文章推荐
- LeetCode 笔记系列13 Jump Game II [去掉不必要的计算]
- LeetCode 45 Jump Game II
- LeetCode - Jump Game II
- Leetcode_jump-game-ii(c++ and python version)
- LeetCode - Jump Game II
- Jump Game II -- leetcode
- [leetcode] Jump Game II
- leetcode 45.Jump Game II
- leetcode - 45.Jump Game II
- [LeetCode]Jump Game II
- 【LeetCode】Jump Game II 跳跃游戏II - 贪心 Medium
- Leetcode:Jump Game II
- LeetCode Jump Game && Jump GameII
- *LeetCode-Jump Game II
- 136_leetcode_Jump Game II
- 【一天一道LeetCode】#45. Jump Game II
- leetcode_question_45 Jump Game II
- [leetcode 45] Jump Game II
- LeetCode——Jump Game II
- [Leetcode] Jump Game II