FTPrep: 45 Jump Game 2

来源:互联网 发布:卖家加入淘宝客要求 编辑:程序博客网 时间:2024/05/19 18:00

这题关键是说了一定会reach to end,所以代码相对可以简单点。

代码:

public class Solution {    public int jump(int[] nums) {        int len=nums.length;        if(len==0) return 0;        int updatedReach=0;        int step=0;        int currReach=0;        for(int i=0; i<len-1; i++){           // don't need to care about the last step. As the description says, it can always jump to the last;            updatedReach=Math.max(updatedReach, i+nums[i]);            if(i==currReach){                step++;                currReach=updatedReach;            }        }        return step;    }}



如果改变要求,说如果达不到end,那么就return 0,这样的话其实更general,参考ganker的代码。在for loop中设置两个出口。一个是end,一个是maxReach

原创粉丝点击