Leetcode题解:55. Jump Game

来源:互联网 发布:linux 发送arp广播包 编辑:程序博客网 时间:2024/06/06 07:36

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.

难度:Medium

解题思路:用一个变量maxl来记录当前可以最远到达的下标,对于每一个下标小于maxl的位置都是可以被访问到的。那么可以将maxl初始化为向量nums的第一个数。遍历一遍向量nums,判断当前下标i是否小于maxl,如果小于则表示这个点可以到达,比较i+nums[i]与maxl的大小并且更新maxl值。 一旦maxl不小于最后一个元素的下标的话,那么就可以return true; 如果遍历了整个数组而没有retrun true的话,就在循环外return false.

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

0 0
原创粉丝点击