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.

思路:我觉得关键是对每一步上元素值与本身索引相加后,索引能达到的最大值,判断这个最大值能否到达最后一个元素。这个时间复杂度是O(n).

class Solution {
public:
    bool canJump(int A[], int n) {
        if(n<=0)
            return true;
        int j=0;
        for(int i=0;i<n;i++)
        {
            if(i+A[i]>j)
                j=A[i]+i;
            if(j>=n-1)
                return true;
            if(j==i)
                return false;
        }
    }
};

 解法二:时间复杂度为O(n2),思路依然是每次判断本身索引和其元素值累加后的最大值。

class Solution {
public:
    bool canJump(int A[], int n) {
        if(n<=1)
            return true;
        int begin=0;
        int end=0;
        for(;end<n-1;)
        {
            int newEnd=begin;
            for(int i=begin;i<=end;i++)
            {
                newEnd=max(newEnd,i+A[i]);
            }
            if(newEnd==end)
                return false;
            begin=end+1;
            end=newEnd;
        }
        if(end>=n-1)
            return true;
        else
            return false;
    }
};

 

posted @ 2014-04-11 08:56  Awy  阅读(192)  评论(0编辑  收藏  举报