LeetCode 第四十五题(Jump Game II)Java

来源:互联网 发布:淘宝直通车掌柜热卖 编辑:程序博客网 时间:2024/06/06 14:09

原题:

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

思路:

用一个变量curRch记录下当前步数最远能走到哪里;

用一个变量curMax依次遍历,得到以某一位置下能到达的最远位置;

如果遍历到 i 位置,curRch到达不了的话,说明此时要多走一步到 i 位置,并更新curRch;

记录步数并返回;


代码:

public class Solution {    public int jump(int[] nums) {        int Length=nums.length;        int times=0;        int curRch=0;        int curMax=0;        for(int i=0;i<Length;i++){            if(curRch<i){                times++;                curRch=curMax;            }            curMax=Math.max(curMax,nums[i]+i);        }        return times;    }}


看过一次解法,这次仍然没能想透彻。。。
0 0
原创粉丝点击