LeetCode解题报告 55. Jump Game [medium]

来源:互联网 发布:宁波淘宝美工培训 编辑:程序博客网 时间:2024/05/16 02:34

题目描述

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.

解题思路

利用贪心算法,贪心算法正确的条件是,每一步的最优解一定包含上一步的最优解。
在本题中,在每一个位置上,从该位置出发,所能达到的最大范围是i+nums[i]。
如果在该范围中,有能到达的更大的范围,则选择用新的最大范围;
当这个范围大于或等于最后一位的位置时,则返回true;
当这个范围无法到达遍历过程中的第i位时,则最大范围都到不了,就没有能到达的了,返回false。

复杂度分析

时间复杂度为O(n)。

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



0 0
原创粉丝点击