[LeetCode] 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.)
int jump(int A[], int n)
{
int pos = 0;
int nextPos = 0;
int count = 0;
while (true)
{
pos = nextPos;
int span = 0;
for (int j = 1; j <= A[pos]; j++)
{
int temp = pos + j;
if (temp+A[temp] > span)
{
nextPos = temp;
span = temp + A[temp];
}
}
count++;
if (nextPos >= n-1)
{
return count;
}
}
}
相關文章
- Leetcode jump Game IILeetCodeGAM
- Leetcode-Jump Game IILeetCodeGAM
- Jump Game II leetcode javaGAMLeetCodeJava
- [LeetCode] 45. Jump Game IILeetCodeGAM
- Leetcode jump GameLeetCodeGAM
- LeetCode 55 Jump GameLeetCodeGAM
- Leetcode-Jump GameLeetCodeGAM
- Jump Game leetcode javaGAMLeetCodeJava
- [LeetCode] 55. Jump GameLeetCodeGAM
- 【leetcode】45. Jump Game II 非負陣列的最少跳躍步數LeetCodeGAM陣列
- Jump Game(C++)GAMC++
- 55-jump Game 跳躍遊戲GAM遊戲
- 【Leetcode】1340. Jump Game V 【動態規劃/記憶性搜尋】LeetCodeGAM動態規劃
- LeetCode:Game of LifeLeetCodeGAM
- LeetCode-Game of LifeLeetCodeGAM
- LeetCode-Nim GameLeetCodeGAM
- Leetcode 292. Nim GameLeetCodeGAM
- Leetcode Spiral Matrix IILeetCode
- Leetcode Path Sum IILeetCode
- Leetcode-Subsets IILeetCode
- Leetcode-Permutations IILeetCode
- Leetcode Unique Paths IILeetCode
- Permutations II leetcode javaLeetCodeJava
- Subset II leetcode javaLeetCodeJava
- LeetCode-Design Snake GameLeetCodeGAM
- leetcode-90. Subsets IILeetCode
- Leetcode 213 House Robber IILeetCode
- LeetCode-Strobogrammatic Number IILeetCode
- LeetCode-Course Schedule IILeetCode
- LeetCode-H index IILeetCodeIndex
- LeetCode-Majority Element IILeetCode
- LeetCode-Basic Calculator IILeetCode
- LeetCode-Word Pattern IILeetCode
- LeetCode-Paint House IILeetCodeAI
- Leetcode: Arithmetic Slices II - SubsequenceLeetCode
- LeetCode 59 Spiral Matrix IILeetCode
- LeetCode-House Robber IILeetCode
- LeetCode-Number of Islands IILeetCode