leetcode45. Jump Game II

本文介绍了一种算法,用于计算从数组起始位置到达末尾所需的最少跳跃次数。通过选择每次跳跃能够达到的最远距离来优化路径。

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

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

解题思路:这个题主要就是找到nums[i]的下一个位置,nums[i]的下一个位置肯定是在[ i+1,i+nums[i] ]的范围内的,我们只要保证找到的位置可以跳到的下一个位置的距离最远即可,也就是说需要保证max1-i+nums[max1]最大即可,这里假设max1为当前位置跳到下一位置的索引。而当有相等的值的时候,选当前位置跳最远的。

然后还需要考虑一个边界的问题,如果当前位置的最远距离已经可以调到数组最后,直接count++,然后return count即可!

class Solution {

    public int jump(int[] nums) {
        int count = 0;//返回值
        for(int i = 0;i<nums.length;){//对数组进行遍历
            int k = nums[i];
            if(i+1<nums.length){//边界控制
                int max1 = i+1;
                int sum =0;         
                if(i+k>=nums.length-1){ //当nums[i]的值已经可以一步调到数组末尾,即可直接返回count
                    count++;
                    return count;
                }
                for(int j = i+1;j<=i+k;j++){//对下一个位置的选择
                    if(j>=nums.length){
                        count++;
                        return count;
                    }
                    else{
                        int sum1=j-i+nums[j];
                        if(sum1>sum){
                            max1 = j;
                            sum = sum1;
                        } 
                    }
                }
                i = max1;
                count++;
            }
            else{
                return count;
            }
        } 
        return count;
    }

}

另一种解法:

这里只要保证i+A[i]最大即可,for里面的if,是来判断跳到哪一个位置!

class Solution {
    public int jump(int[] A) {
    int sc = 0;
    int e = 0;
    int max = 0;
    for(int i=0; i<A.length-1; i++) {
        max = Math.max(max, i+A[i]);
        if( i == e ) {
            sc++;
            e = max;
        } 
    }
    return sc;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值