leetcode 45. 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.)
Note:
You can assume that you can always reach the last index.
题意:
就当有N块石头吧,在第i块石头上最远可以跳nums[i]块石头,问最少跳多少次可以从第一块石头跳到最后一块。
思路:
目测数据范围很大,要用O(N)的方法。
设far为从0-i的石头上最远可以跳到哪里。
prePos 为在跳ans步的时候,最远可以跳到什么地方。
则当i>prePos时,跳ans步已经跳不到i点了,我们需要++ans,并修改prePos为0~i-1最远可以跳到的地方,我们知道far为之前的点最远可以跳到的位置,这个跳包括跳跃次数为ans+1的和<=ans的,因此跳ans+1步最远可以跳到的位置就是prePos。
class Solution { public: int jump(vector<int>& nums) { if(nums.size() <= 1) return 0;int far = 0, prePos = 0, ans = 0; for(int i = 0; i < nums.size(); i++){ if( i > prePos){ ans ++; prePos = far; } far = max(far, i + nums[i]); } return ans; } };