leetcode之jump game

来源:互联网 发布:sql怎么备份数据库 编辑:程序博客网 时间:2024/05/29 07:38

题目:

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.

解答:

直接贪心的思路,不断的更新可以到达的位置的最右边界即可

class Solution {public:    bool canJump(vector<int>& nums) {     int limit = nums[0];     int size = nums.size();     int pos = 0;     while(pos < size && pos <= limit)     {         pos++;         if(pos <= limit && nums[pos] + pos > limit)            limit = nums[pos] + pos;     }     return (limit >= size - 1);    }};


0 0
原创粉丝点击