题目链接:45. 跳跃游戏 II - 力扣(LeetCode)
前段时间看完程序员卡尔的讲解视频时,就是一知半解的状态,过两天复盘想重新写的时候,发现思路有,但是很难写出来。最终根据思路来,发现了一种半新套路。主要针对的是循环条件。
class Solution {
public int jump(int[] nums) {
int res = 0;
int maxDistance = 0;
int curDistance = 0;
int maxTemp=0;
if (nums.length == 1) {
return 0;
}
for (int i = 0; i <= curDistance; i++) {
int temp = i + nums[i];
if (temp >= maxDistance) {
maxDistance = temp;
maxTemp=i;
}
if (temp >= nums.length - 1) {
return res + 1;
}
if (i == curDistance) {
res++;
curDistance = maxDistance;
i=i-maxTemp-1;
}
}
return res;
}
}
先走一步,如果当前跳跃能到的最远的地方却还是不能到终点,则开始走第二步。此处第二步其实就是回头路。