LeetCode 45. Jump Game II 跳跃游戏2

Question:

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.

思路:

贪心算法。只有在不得不跳的时候if(jump>max_index),才跳一步,选择下一次可达最远的地方跳,并把每次跳跃点的next_num[jump]记录在max_index中,因为是判断条件,所以不能随意更新,寻找路径中最大的next_num用next_max_index更新,并在每次跳跃时if(jump > max_index )才更新 max_index = next_max_index;。

第一次写出现了很多错误,需要再次思考几次,理清原因。

class Solution {
    public int jump(int[] nums) {
        int len = nums.length;
        if(nums[0]<1 || len < 2) //如果数组长度小于2或者num[0]=0 ,返回0,因为要么不用跳跃,要么无法跳跃到后一个点
           return 0;
        int[] next_nums = new int[len];
        for(int i=0; i<len; i++)
        {
            next_nums[i] = i+nums[i];
        }
        
        int jump = 0;
        int max_index = next_nums[0];
        int next_max_index =next_nums[0];
        int jump_times = 0;
       // while(jump < len && next_max_index < len )错误 [1,2,3] wrongout:1 correct answer:2
        while(jump < len)
        {      
            //if(jump == max_index ) 错误
            if(jump > max_index )
            {
                jump_times++;
                max_index = next_max_index;
            }
            if(next_max_index < next_nums[jump])
              next_max_index = next_nums[jump];
            jump++;
        }
       //错误的if Input:  [5,9,3,2,1,0,2,3,3,1,0,0]
       //Output:  0
       //Expected:  3
        //if(next_max_index < len)
       //     return 0;  //到不了,返回0                                 
      //  else    
            return ++jump_times;
    }
}

博主学习笔记,转载请注明出处,谢谢~


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值