By
yusijia
Updated:
1 2 3 4 5 6 7 8 9 10
| 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.)
|
题意:
从左边往右边跳,用最小的步数跳到最右边,到i点时,下次能跳的最远距离为A[i]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class Solution { public: int jump(vector<int>& nums) { if(nums.size() == 1){ return 0; } int n = nums.size(); step 跳的步数 index 当前位置i与跳出nums[i]距离范围内的点 distance 目前在的位置 rightest_distance 下次能跳到的最远边界 */ int step = 1, index = 0, distance = nums[0]; while(distance < n-1){ int rightest_distance = distance; while(index <= distance && index < n){ rightest_distance = max(rightest_distance, index + nums[index]); index++; } if(rightest_distance <= distance){ return -1; } distance = rightest_distance; step++; } return step; } };
|