第十三周 leetcode Add to List 55. Jump Game(Medium)

来源:互联网 发布:淘宝卖家怎么激活 编辑:程序博客网 时间:2024/06/03 21:13

题目描述:

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.

解题思路:

贪心算法:
maxdistance记录当前步i之前的,能够跳到的最大距离。nums[i]+i 代表从当前步能够挑到的最大距离。
用max(maxdistance, nums[i]+i)不断更新maxdistance,若maxdistance 小于 n-1,说明无法跳到最后的位置。

代码:

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

代码运行结果:
这里写图片描述

原创粉丝点击