[leetcode 55. Jump Game]week 7

来源:互联网 发布:黄金利多利空数据软件 编辑:程序博客网 时间:2024/06/04 18:36

一、题目

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)


原创粉丝点击