码迷,mamicode.com
首页 > 其他好文 > 详细

跳跃游戏

时间:2020-05-05 00:51:13      阅读:58      评论:0      收藏:0      [点我收藏+]

标签:i++   for   code   span   bsp   思想   problem   下标   整数   

给定一个非负整数数组,你最初位于数组的第一个位置。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

你的目标是使用最少的跳跃次数到达数组的最后一个位置。

示例:

输入: [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
  从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
说明:

假设你总是可以到达数组的最后一个位置。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jump-game-ii

用贪心思想动态维护!!!!

class Solution {
public:

    int jump(vector<int>& nums) {
        int n=nums.size();
        int step=0;
        int maxpos=0;
        int end=0;
        for(int i=0;i<n;i++)
        {
            if(end>=i) maxpos=max(maxpos,i+nums[i]);
            if(end==i&&end!=n-1)
            {
                step++;
                end=maxpos;
            }

        }
        return step;

        
    }
};

 

跳跃游戏

标签:i++   for   code   span   bsp   思想   problem   下标   整数   

原文地址:https://www.cnblogs.com/Charls/p/12829022.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!