LeetCode 55. Jump Game

来源:互联网 发布:洪厚甜网络书法 编辑:程序博客网 时间:2024/06/16 02:37

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.

设立flag为当处在i下标的时候,前面所能够达到的所有长度的最大值(因为是最大值,所以0~最大值的所有下标都可以遍历到)。因此,判断最后能够到达的距离是否大于nums.size()-1。

class Solution {public:    bool canJump(vector<int>& nums) {        int flag=0;        for(int i=0;i<nums.size()&&i<=flag;i++){            flag=max(flag,i+nums[i]);        }        return flag>=nums.size()-1;    }};

原创粉丝点击