您的位置:首页 > 其它

[LeetCode] Jump Game 数组控制

2014-11-28 05:47 441 查看
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
.

Hide Tags

Array Greedy

题目很简单,思路如下:

创建一个标记为last,表示A数组下标为last 前的位置都可以达到,初始化为 1.

从左遍历数组,当前位置加上可跳跃的长度A[i] 更新last。

如果last >= n ,即可以达到数组末尾,否则失败。

我写的如下:

#include <iostream>
using namespace std;

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

int main()
{
int A[] = {3,2,1,1,4};
Solution sol;
cout<<sol.canJump(A,sizeof(A)/sizeof(int))<<endl;
return 0;
}


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