【leetcode】Jumping Game (Greedy)

Given an array of non-negative integers, you are initially at the first position of the array.

Each element in the array represents the maximum length you can jump at that position.

Determine if you can reach the last position.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: We can jump 1 step first, from position 0 to position 1, and then jump 3 steps from position 1 to the last position.
Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: No matter what, you will always reach the position at index 3. But the maximum jump length for that position is 0, so you can never get to the last position.

Link: https://leetcode-cn.com/problems/jump-game

Thought analysis:

In fact, when I first read this question, I had a hunch that it was greedy.
Each element in the array represents the maximum length you can jump at that position, which means that the point you can jump is an interval [cur,cur+nums[cur]. We can consider updating this interval every time you take a step. This is to push from the local optimal solution to the global optimal solution.
Therefore, defining a Max represents the farthest point that can be jumped to among all the points currently jumped. If the current point cur > Max means that it is out of bounds, return false. If you can go through all the points or when Max >= n-1you can directly return true.

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int Max = 0, n = nums.size();
        for(int i = 0;i < n;i++)    //Max表示前面走的所有位置中能跳的最远的位置
        {
            if(i > Max) return false;   //如果走的位置>Max,表示不合法
            Max = max(Max,i+nums[i]);   //每走一个位置,更新一次Max
        }
        return true;
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325582656&siteId=291194637