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.

大致题意:
给定一组非负整数数组,从数组第一个位置开始跳,你所在位置的数就是每次跳跃能前进的最多长度。求最少多少次跳跃能跳到最后一个下标,假设解存在。


Jump Game I 基本一样,都可以用贪心或者动态规划解决。贪心的思路简单地说是:遍历一遍数组,不断比较当前下标位置能跳到的最远下标与之前遍历过程中记录的最远下标位置。如果当前下标超过了之前记录的位置,跳跃次数+1。返回条件就是当前能达到的最远位置>=最大下标值,则返回当前记录的跳跃次数,一定是最小值。

class Solution {
public:
    int jump(vector<int>& nums) {
        int ans = 0, curMax = 0, lastMax = 0;
        for (int i = 0; i < nums.size() && curMax < nums.size() - 1; i++) {
            if (i > curMax) {
                curMax = lastMax;
                ans++;
            }
            lastMax = max(lastMax, i + nums[i]);
        }
        return ans;
    }
};

原题地址:https://leetcode.com/problems/jump-game-ii/description/

老实说,我觉得这题面试基本不会考。。做着玩吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值