Leetcode 算法习题 第十周

来源:互联网 发布:java获取服务器ip地址 编辑:程序博客网 时间:2024/06/06 03:02

55. Jump Game

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 max = 0;        int i;        for(i = 0; i < nums.size(); i++){            if(i>max) return false;            max = (nums[i]+i > max ? nums[i]+i : max);        }//贪心算法:每次走最远的距离,如果能够走的更远就说明是一个好的行走。        return true;    }};
原创粉丝点击