LeetCode: Jump Game

来源:互联网 发布:mac怎么玩免费的游戏 编辑:程序博客网 时间:2024/06/05 16: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.

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


Round 2:

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


0 0
原创粉丝点击