前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【LeetCode】45. Jump Game II

【LeetCode】45. Jump Game II

作者头像
韩旭051
发布2019-11-07 22:33:49
4150
发布2019-11-07 22:33:49
举报
文章被收录于专栏:刷题笔记

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/shiliang97/article/details/102785855

【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.

Example:

Input: [2,3,1,1,4] Output: 2 Explanation: 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.

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/jump-game-ii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

感觉这种题目叫做贪心?

CPP

代码语言:javascript
复制
class Solution {
public:
    int jump(vector<int>& nums) {
        int step=0,maxsize=0,end=0;
        for(int i=0;i<nums.size()-1;i++){
            maxsize=max(maxsize,nums[i]+i);
            if(i==end){
                end=maxsize;
                step++;
            }
        }return step;
    }
};

大佬的答案,优化了点?

代码语言:javascript
复制
class Solution {
public:
    int jump(vector<int>& nums) {
        if(nums.size()<=1) return 0;
        int end = nums[0];
        int maxpos = nums[0];
        int cnt= 0;
        for(int i = 0; i < nums.size();++i)
        {
            if(i>end)
            {
                cnt++;
                end = maxpos;
                
            }
            maxpos = max(maxpos,i+nums[i]);
        }
        return ++cnt;
    }
};

java

代码语言:javascript
复制
class Solution {
   public int jump(int[] nums) {
    int end = 0;
    int maxPosition = 0; 
    int steps = 0;
    for(int i = 0; i < nums.length - 1; i++){//找能跳的最远的
        maxPosition = Math.max(maxPosition, nums[i] + i); 
        if( i == end){ //遇到边界,就更新边界,并且步数加一
            end = maxPosition;
            steps++;
        }
    }
    return steps;
   }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/10/28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 【LeetCode】45. Jump Game II
  • 感觉这种题目叫做贪心?
  • CPP
  • 大佬的答案,优化了点?
  • java
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档