您的位置:首页 > 其它

[Leetcode 56] 55 Jump Game

2013-05-26 08:00 465 查看
Problem:

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
.

Analysis:

At first glance, it seems like a backtracking problem. But won't pass the large test cases.

Then try to use simulation method, though can go further than backtracking, still can pass all test cases.

The developed a one-scan algorithm. Observe that we can compute what's the furthest position we can go at each position. If the current position is less than the max position we can go, then it means that we can reach this place. And if from this place go to the furthest place we can go is greater than max. Then it means that the range is extended. We can continue this process until 1. reach the end of the array; 2. find the max covers the final place. Since we only need to scan the array only once, the total time complexity is O(n)

Code:

Backtracking Solution: TLE

class Solution {
public:

bool canJump(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (n==0) return false;

int max = 1+A[0];
for (int i=2; i<+n; i++) {
if (i<=max && (i+A[i-1]) > max) {
max = i+A[i-1];
}

if (max >= n)
break;
}

return (max >= n);
}
};


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: