55. Jump Game


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.

Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

问题描述&解题思路:题目意思是说给一段非负的数字,起始位置在index=0的地方,nums[index]表示你在当前的index下,最多能走nums[index]步,走到nums[index]+index的位置。于是使用贪心算法,假设你当前处于第index的位置,那么对于你能走到的位置做一个遍历从index+1一直到index+nums[index],其中找到能继续走的最远的(能继续走的最远的可能能比没走的那么远的有更多的选择,比如当前能走的步数为2,nums[index+1]为5,而nums[index+2]为3,那么1+5>2+3,走到index+2之后的选择比走到index+1的要少,所以选择走到index+1。

bool canJump(vector<int>& nums) {
        int size = nums.size();
        int curIndex = 0;
        while (1) {
            //当前max = 当前能跳的最远路径
            int max = nums[curIndex];
            int maxIndex = curIndex;
            //对于能到的路径进行搜索,如果能到的位置继续跳能比当前最远的路径远,那么设置它为max,同时记录下标maxIndex
            for (int i = 1; i <= nums[curIndex]; i++) {
                if (i + nums[curIndex+i] >= max) {
                    max = i + nums[curIndex+i];
                    maxIndex = i + curIndex;
                }
            }
            //cout << max << endl;
            //maxIndex + nums[maxIndex]就是这一步最远的能到的位置
            if (maxIndex + nums[maxIndex] >=  size-1)
                return true;
            if (curIndex == maxIndex)
                return false;
            curIndex = maxIndex;
        }
    }

思路二:

从前往后逐个遍历元素,计算每个位置可以到达的最远距离。如果最远距离不能到达该位置说明不能到达终点。如果中间某处的最远距离大于末尾位置 说明可以达到终点

 public boolean canJump(int[] nums) {
        if(nums==null||nums.length==0)
            return false;
        int max = nums[0];
        for(int i=1;i<nums.length;i++){
            if(max<i)
                return false;
            else{
                max = Math.max(max,i+nums[i]);
                if(max>nums.length-1)
                    return true;
            }
        }
        return true;
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值