**一. 题目描述**
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.)
**二. 题目分析**
该题的大意是,给定一个数组,每个元素代表从该位置可以往后跳的距离,问从第一个位置跳到最后一个位置至少需要跳多少次。
与 Jump Game 有所不同的是,Jump Game 询问该数组能否跳到最后一格,这道题要求算出跳的次数。解决的思路依旧是贪心,只需设置一个数组用来记录跳的路径即可。
**三. 示例代码**
~~~
class Solution {
public:
int jump(int A[], int n)
{
int result = 0; // 当前已跳跃的次数
int last = 0; // 上一跳可达到的最远距离
int curr = 0; // 当前一跳可达到的最远距离
for (int i = 0; i < n; ++i)
{
// 无法向前继跳直接返回
if(i > curr)
return -1;
// 需要进行下次跳跃,则更新last和当前已执行的跳数result
if (i > last)
{
last = curr;
++result;
}
// 更新当前可跳达的最远处
curr = max(curr, i+A[i]);
}
return result;
}
};
~~~
**四. 小结**
类似的解题思路还有BFS,后期可以验证验证。
- 前言
- 2Sum
- 3Sum
- 4Sum
- 3Sum Closest
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array II
- Search in Rotated Sorted Array
- Remove Element
- Merge Sorted Array
- Add Binary
- Valid Palindrome
- Permutation Sequence
- Single Number
- Single Number II
- Gray Code(2016腾讯软件开发笔试题)
- Valid Sudoku
- Rotate Image
- Power of two
- Plus One
- Gas Station
- Set Matrix Zeroes
- Count and Say
- Climbing Stairs(斐波那契数列问题)
- Remove Nth Node From End of List
- Linked List Cycle
- Linked List Cycle 2
- Integer to Roman
- Roman to Integer
- Valid Parentheses
- Reorder List
- Path Sum
- Simplify Path
- Trapping Rain Water
- Path Sum II
- Factorial Trailing Zeroes
- Sudoku Solver
- Isomorphic Strings
- String to Integer (atoi)
- Largest Rectangle in Histogram
- Binary Tree Preorder Traversal
- Evaluate Reverse Polish Notation(逆波兰式的计算)
- Maximum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Longest Common Prefix
- Recover Binary Search Tree
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal II
- Binary Tree Zigzag Level Order Traversal
- Sum Root to Leaf Numbers
- Anagrams
- Unique Paths
- Unique Paths II
- Triangle
- Maximum Subarray(最大子串和问题)
- House Robber
- House Robber II
- Happy Number
- Interlaving String
- Minimum Path Sum
- Edit Distance
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
- Decode Ways
- N-Queens
- N-Queens II
- Restore IP Addresses
- Combination Sum
- Combination Sum II
- Combination Sum III
- Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- Longest Consecutive Sequence
- Word Search
- Word Search II
- Word Ladder
- Spiral Matrix
- Jump Game
- Jump Game II
- Longest Substring Without Repeating Characters
- First Missing Positive
- Sort Colors
- Search for a Range
- First Bad Version
- Search Insert Position
- Wildcard Matching