55. Jump Game

来源:互联网 发布:房地产动画制作软件 编辑:程序博客网 时间:2024/06/08 14:50

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.

For example:

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

代码如下:

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

解题思路:

  • 需理解当可以到达某个点时,那么必定能够到达这个点之前的所有点;
  • 用变量 canGet 记录当前可以到达的点的下标,最初位于0处,则必定可以到达第一个点,给 canGet 赋值为0;
  • 接下来计算每个点可以到达的点,并且 canGet 的值总是可以到达的最大值,如果当前到达的点的下标小于 canGet 则说明不能到达当前点,返回 false,退出游戏;
  • 整个过程若直到最后一个点也没有退出游戏,则说明可以到达最后一个点,返回 true。
原创粉丝点击