Jump Game II

原题链接:https://leetcode.com/problems/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.

For example:
Given array A = [2,3,1,1,4]

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

Solution: 这道题可以使用贪心法来求解,对当前所在位置current,它下一步所能到达位置的范围是[current + 1, current + A[current]。我们在这个区间中选择一个位置作为下一步的终点next,使得在区间[current + 1, current + A[current]中,next能走的下一步最远(也就是next + A[next]的值最大)。这样,通过每一步选择能走最远的索引值,找到最小步数。

class Solution {
public:
    int jump(vector<int>& nums) {        
        int n = nums.size();
        if (n == 1) return 0;

        int nextIndex = 0;  // 下一步要去的地方
        int maxIndex = 0;   // 下一步能到达的最远的地方
        int steps = 0;
        for (int i = 0; i < n; ) {
            int s = i + 1;
            int e = min(i + nums[i], n-1);

            if (e == n-1) return steps + 1;

            while (s <= e) {
                if ((s + nums[s]) > maxIndex) {
                    nextIndex = s;
                    maxIndex = s + nums[s]; 
                }
                s++;
            }

            i = nextIndex;

            steps++;         
        }  
    }
};

算法分析: 当选择的下一步终点next的值在区间[current + 1, current + A[current]的靠左位置,则为next寻找下一步时,会造成大量的重复操作。

改进:

class Solution {
public:
    int jump(vector<int>& nums) {
        int n = nums.size(), step = 0, start = 0, end = 0;
        while (end < n - 1) {
            step++; 
            int maxend = end + 1;
            for (int i = start; i <= end; i++) {
                if (i + nums[i] >= n - 1) return step;
                maxend = max(maxend, i + nums[i]);
            }
            start = end + 1;
            end = maxend;
        }
        return step;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值