45.Jump Game II---贪心---2018大疆笔试题

题目链接

题目大意:与55题类似,只是这里要求出跳数。

法一(借鉴):贪心。cur表示当前能到达的最远距离,pre表示上一次能到达的最远距离,每到一个位置更新一次最远距离cur,如果当前位置超过了上一次能到达的最远距离,则更新跳数和上一次能到达的最远距离。代码如下(耗时6ms):

 1     public int jump(int[] nums) {
 2         int cur = 0, res = 0, pre = 0;
 3         for(int i = 0; i < nums.length; i++) {
 4             //如果当前位置超过了上一次可以达到的最远距离,更新跳数和上一次可达到的最远距离
 5             if(i > pre) {
 6                 pre = cur;
 7                 res++;
 8             }
 9             //更新当前最远距离
10             cur = Math.max(cur, i + nums[i]);
11         }
12         return res;
13     }
View Code
原文地址:https://www.cnblogs.com/cing/p/9294924.html