Greedy--Jump Game (Medium)

原题


  • Problem Description

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.

  • Sample Input

    [2,3,1,1,4]
    [3,2,1,0,4]

  • Sample Output
    true
    false
  • 解题思路:

    贪心:

    在当前位置,判断可跳至的最远位置之前的位置中,哪些位置是可以跳到更远
    然后选取可以跳至最远的位置,更新为当前位置;
    然后重复此过程,直至能够跳至结尾。

    代码思路:

    1、遍历数组,每次寻找可以到达的更远位置,然后更新数据。
    2、循环终止条件:遍历到数组结尾 + 无法跳至比更远位置再远的位置。

    代码:

    #include <vector>
    using namespace std;
    class Solution {
    public:
        bool canJump(vector<int>& nums) {
            vector<int> index;//最远可跳至的位置【动态数组】
            for (int i = 0; i < nums.size(); i++)
                index.push_back(i + nums[i]);
            int jump = 0;//当前位置
            int max_index = index[0];//当前可到达的最远的位置
            while (jump <= nums.size() - 1 && jump <= max_index)
            {//如果当前位置<=数组最后一个位置&&当前位置<=当前可到达的最远的位置
                if (max_index < index[jump])
                    max_index = index[jump];//逐个位置扫描,对可跳的最远位置进行更新
                jump++;
            }
            if (jump == nums.size())//若当前位置达到数组最后一个位置
                return true;
            return false;
        }
    };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值