您的位置:首页 > 其它

[leetcode 55. Jump Game]week 7

2017-07-07 01:58 453 查看
一、题目

Given anarray of non-negative integers, you are initially positioned at the first indexof the array.
Each element in the array represents your maximum jumplength 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 maxjump=1;

       for (int i=0;i<maxjump;i++)

{

           if (maxjump>nums.size())

           break;

           if (i+nums[i]+1 > maxjump)

           maxjump=i+nums[i]+1;

       }

       if (maxjump>=nums.size())

       return true;

       else

       return false;

    }

};

三、思路

要到达最后一步则判断每一步后更新的可到达最大步数即可,所以用贪婪算法从第一步起每走一步比较原最大值与i+A[i]+1并更新,到最后若最大值大于容器大小(即最后一步)即可。此种解题方法时间复杂度为O(n)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: