博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 55. Jump Game 解题报告
阅读量:2359 次
发布时间:2019-05-10

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

LeetCode 55. Jump Game 解题报告

题目描述

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.


示例

Example :

A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.


注意事项

没有。


解题思路

我的思路:

这道题没有考什么特别的知识点,就是普通的数组题目。我的思路是设置一个起点start和终点end,每次循环过程都在[start, end]范围内找到能够到达的最远点nextEnd,然后更新start=end,end=nextEnd,当end <= start就结束循环,此时存在两种情况,第一种是nextEnd大于等于数组最后一个下标值,就表明能够到达。第二种是nextEnd小于数组最后一个下标值,表明不能到达。

参考思路:

通过之后查看了其他人的代码,发现这个题目能够有更简洁的解法,核心同样是尽可能地到达更远的下标,所以只要一个循环,更新能够达到的下标值就行,最后判断最远的下标值是否为数组最后一个下标值。


代码

我的代码:

class Solution {public:    bool canJump(vector
& nums) { if (nums.empty()) return false; int start = 0, end = nums[start], nextEnd = 0; while (end > start) { nextEnd = end; for (int i = start; i <= end && i < nums.size(); i++) { if (i + nums[i] > nextEnd) nextEnd = i + nums[i]; } start = end; end = nextEnd; } if (end >= nums.size() - 1) return true; return false; }};

参考代码:

class Solution {public:    bool canJump(vector
& nums) { int i = 0; for (int reach = 0; i < nums.size() && i <= reach; ++i) reach = max(i + nums[i], reach); return i == nums.size(); }};

总结

这道题是不难,关键是知道需要更新能够到达的最远下标,并用最远下标与最后一个下标进行比较就能通过。

这周题的暂且先做这一道水水的题目,与其他人的代码对比,还是感觉自己的算法能力不太行,得坚持刷题,并且多想想怎么优化自己的代码,加油~

转载地址:http://jqntb.baihongyu.com/

你可能感兴趣的文章
Android模拟器无法上网问题
查看>>
抱歉,进程android.process.media,已停止运行的解决办法
查看>>
第一个helloword小例
查看>>
oracle新建方案
查看>>
android的坑
查看>>
java.net.SocketException:socket failed:EACCES (Permission denied)
查看>>
android.os.NetworkOnMainThreadException
查看>>
Android:单元测试Junit的配置
查看>>
国际产业
查看>>
制造业
查看>>
混沌的有关概念——1
查看>>
混沌的有关概念——2
查看>>
混沌理论的简要观点
查看>>
知识的经济学分析:一个文献综述——基于范式演进的视点
查看>>
reading the path of picture
查看>>
Could a 32bit software install on a 64bit-system computer
查看>>
No reship system to recovery disk AHCI diriven and just do it
查看>>
debug compare with release
查看>>
QT5.7 deploys opencv2.4.13(the version of opencv is not newer than QT)
查看>>
the principle of laplacian filter
查看>>