博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Leetcode] jump game 跳跃游戏
阅读量:4354 次
发布时间:2019-06-07

本文共 1351 字,大约阅读时间需要 4 分钟。

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.

Determine if you are able to reach the last index.

For example:

A =[2,3,1,1,4], returntrue.

A =[3,2,1,0,4], returnfalse.

 题意:给定以非零整数组成的数组,每个值代表可以跳过的距离,问能否到达最后

思路:找到某一时刻能到达的最远距离maxlen,若该值大于等于n-1说明从这个地方能够直接跳到最后;若当前数组中的值为0,而最大值maxlen不能跳过这个点说明不能达到最后;一般情况是,当前数组元素的下标加上对应值和maxlen对比,若大于则更新maxlen。代码如下:

1 class Solution { 2 public: 3     bool canJump(int A[], int n)  4     { 5         if(n==0)    return true; 6          7         int maxLen=A[0]; 8         for(int i=0;i
=n-1)11 return true;12 else if(A[i]==0&&maxLen<=i)13 return false;14 else15 maxLen=max(i+A[i],maxLen);16 }17 return false; 18 }19 };

 

还有一种思路是:定义一个当前等达到的最大距离maxlen,那该值之前的所有点都是可以达到的,在遍历之前的这些点的过程中,更新最远距离maxlen。我们可以通过最远距离是否等于n来判断(当然这个距离要不大于n)。参考。代码如下:

1 class Solution { 2 public: 3     bool canJump(int A[], int n)  4     { 5         int maxLen=0; 6         int i=0; 7         for( ;i<=maxLen&&i
=n)  //不加if判断也可10 return true;11 maxLen=max(maxLen,i+A[i]);12 }13 return (i==n);14 }15 };

 

转载于:https://www.cnblogs.com/love-yh/p/7168914.html

你可能感兴趣的文章
用长微博工具发布长微博
查看>>
大庆金桥帆软报表案例
查看>>
方维分享系统,个人中心杂志社显示我的、关注的、推荐的数量
查看>>
JavaScript BOM加载事件
查看>>
Java复习总结——详细理解Java反射机制
查看>>
Navicat for MySQL10.1.7注册码
查看>>
Proxy模式
查看>>
读书多些会怎样
查看>>
浏览器好用的技术
查看>>
HDU 2188------巴什博弈
查看>>
tp5任务队列使用supervisor常驻进程
查看>>
Xmind?
查看>>
spring+quartz 实现定时任务三
查看>>
day2-三级菜单
查看>>
java retry_java里面的retry:
查看>>
linux下升级4.5.1版本gcc
查看>>
Beanutils
查看>>
FastJson
查看>>
excel4j
查看>>
Thread
查看>>