LeetCode 55. Jump Game

LeetCode 55. Jump Game

Description:

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.

Example:

A = [2,3,1,1,4], return true.

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


分析:

首先,distance为当处在i下标的时候,前面所能够达到的所有长度的最大值,因为是最大值,所以0~最大值的所有下标都可以遍历到;
i <= distance的所有下标都可以遍历,然后更新distance的值为distance = max(distance, i + nums[i]);
最后比较distance和nums.size() - 1的大小,若大于则返回true,表示可以到达最后一个数。

代码如下:

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
bool canJump(vector<int>& nums) {
int distance = 0;
for (int i = 0; i < nums.size() - 1 && i <= distance; i++) {
distance = max(distance, i + nums[i]);
}
return distance >= nums.size() - 1;
}
};
------本文结束感谢阅读------