LeetCode刷题笔记(贪心):jump-game

本是古典 何须时尚 2022-06-01 11:19 242阅读 0赞

  • 转载请注明作者和出处:http://blog.csdn.net/u011475210
  • 代码地址:https://github.com/WordZzzz/Note/tree/master/LeetCode
  • 刷题平台:https://www.nowcoder.com/ta/leetcode
  • 题  库:Leetcode经典编程题
  • 编  者:WordZzzz

    • 题目描述
    • 解题思路
    • C版代码实现

题目描述

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.

给定一个非负整数数组,最初定位在数组的第一个索引处。 数组中的每个元素表示您在该位置的最大跳跃长度。 确定你是否能够达到最后。

解题思路

直接遍历数组,计算能到达的最远距离即可,然后与数组长度作比较,如果超过数组长度,则说明可以走到最后。

C++版代码实现

  1. class Solution {
  2. public:
  3. bool canJump(int A[], int n) {
  4. if(A == NULL || n == 0)
  5. return false;
  6. //maxReach标记能跳到的最远处。
  7. int maxReach = 0;
  8. //maxReach >= i表示此时能跳到i处,0 <= i < n表示扫描所有能到达的点,并计算能达到的最远距离。
  9. for(int i = 0; i < n && i <= maxReach; ++i)
  10. maxReach = max(maxReach, A[i] + i);
  11. //如果最后跳的最远的结果大于等于n-1,那就能跳到最后。
  12. return maxReach < n - 1 ? false : true;
  13. }
  14. };

系列教程持续发布中,欢迎订阅、关注、收藏、评论、点赞哦~~( ̄▽ ̄~)~

完的汪(∪。∪)。。。zzz

发表评论

表情:
评论列表 (有 0 条评论,242人围观)

还没有评论,来说两句吧...

相关阅读