LeetCode--Jump Game

来源:互联网 发布:unity3d 协程重复调用 编辑:程序博客网 时间:2024/05/17 07:00

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.

思路:贪心法。这是之前那个Jump Game II 的低配版,只需要判断是否能到达,一次循环遍历,维护一个变量end即可。

class Solution {public:    bool canJump(vector<int>& nums) {        int n=nums.size(),end=0;        for(int i=0;i<=end;i++){            end=max(end,i+nums[i]);            if(end>=n-1) return true;        }           return false;    }};
原创粉丝点击