LeetCode 55. Jump Game and 45. Jump Game II 题解

本文解析了LeetCode上的两道经典Jump Game问题。第一题介绍如何判断能否从数组起始位置到达末尾,第二题则进一步探讨如何以最少的跳跃次数完成这一目标。文章详细阐述了解决方案的贪心算法思路,提供了简洁高效的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

贪心算法

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

题解

   题目要求从数组nums的最左端走到数组的最右端,数组上每个元素代表最多可以走多少步。贪心的思路如下:

    用nDistance记录当前i之前可以走的最远距离。如果distance< i,即代表即使再怎么走也不能到达i。当到达i时,nums[i]+i,代表从i能走的最远距离,如果该值大于或等于数组大小减一,证明可以到达数组最后的位置。否则,更新nDistance,nDistance=max(nDistance, nums[i]+i)代表能到达的最远距离。

【代码】

    bool canJump(vector<int>& nums) {
    	int nSize = nums.size();
    	if (nSize < 2)
    		return true;
    
    	int nDistance = 0;
    	for (int i = 0; i < nSize && i <= nDistance; i++) {
    	    if (i + nums[i] >= nSize - 1)
    	        return true;
    	    if (nDistance < i + nums[i])
    	        nDistance = i + nums[i];
    	}
    	
    	return false;
    }



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

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

Note:
You can assume that you can always reach the last index.

题解

    与上题不同的地方在于该数组肯定可以从最左端走到最右端,并求出最少步数。难点在于什么时候需要为步数加一,答案是当前的i超过了前一步的最远位置。所以引入nLast变量记录上一步能到达的最远位置。nCur、nStep、nLast的初始值均为0。当遍历到i的时候,如果i超过了nLast(即上一步能到达的最远位置),说明步数需要加1,此时仍需要更新nLast为当前最远位置nCur。全程只需遍历1次数组,而且空间复杂度为常量。

【代码】

    int jump(vector<int>& nums) {
    	int nSize = nums.size();
    	if (nSize < 2)
    		return 0;
    	if (nSize == 2)
    	    return 1;
    
        int nStep = 0;
        int nCur = 0;
        int nLast = 0;
        for(int i = 0; i < nSize; i ++) {
            if(nLast < i) {
                nStep ++;
                nLast = nCur;
            }
            
            if (nums[i] + i > nCur)
                nCur = nums[i] + i;
        }
        return nStep;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值