LeetCode 55. Jump Game (Greedy)

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 1:

Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.

Constraints:

1 <= nums.length <= 3 * 10^4
0 <= nums[i][j] <= 10^5

C++

//I just iterate and update the maximal index that I can reach
class Solution {
public:
    bool canJump(vector<int>& nums) {
    	int i = 0, n = nums.size();
    	for(int reach = 0; i < n && i <= reach; i++){
    		reach = max(i + nums[i], reach);
		}
		return i == n;
    }
};

你可能感兴趣的:(LeetCode 55. Jump Game (Greedy))