1. 程式人生 > 實用技巧 >leetcode95:jump game

leetcode95:jump game

題目描述

給出一個非負整數陣列,你最初在陣列第一個元素的位置

陣列中的元素代表你在這個位置可以跳躍的最大長度 判斷你是否能到達陣列最後一個元素的位置 例如

A =[2,3,1,1,4], 返回 true.

A =[3,2,1,0,4], 返回 false.


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], returntrue.

A =[3,2,1,0,4], returnfalse.


示例1

輸入

複製
[2,3,1,1,4]

輸出

複製
true
示例2

輸入

複製
[3,2,1,0,4]

輸出

複製
false


class Solution {
public:
/**
*
* @param A int整型一維陣列
* @param n int A陣列長度
* @return bool布林型
*/
bool canJump(int* A, int n) {
// write code here
int max=0;
for (int i=0;i<n&&max>=i;++i)
if (i+A[i]>max) max=i+A[i];
return max>=n-1 ?true:false;
}
};