赞
踩
题意描述:
给定一个长度为 n 的 0 索引整数数组 nums。初始位置为 nums[0]。
每个元素 nums[i] 表示从索引 i 向前跳转的最大长度。换句话说,如果你在 nums[i] 处,你可以跳转到任意 nums[i + j] 处:
0 <= j <= nums[i]
i + j < n
返回到达 nums[n - 1] 的最小跳跃次数。生成的测试用例可以到达 nums[n - 1]。
本题与跳跃游戏类似思路,只不过需要找到最小的跳跃步数。移动下标只要遇到当前覆盖最远距离的下标,直接步数加一,不考虑是不是终点的情况。只要让移动下标,最大只能移动到nums.size() - 2的地方就可以了。
完整C++代码如下:
- class Solution {
- public:
- int jump(vector<int>& nums) {
- int end1 = 0;
- int result = 0;
- int end2 = 0;
- for(int i = 0; i < nums.size() - 1; i++){
- end2 = max(nums[i] + i, end2);
- if(end1 == i){
- end1 = end2;
- result++;
- }
- }
- return result;
- }
- };

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。