The greedy algorithm is simple: a jumping game

     Title description:

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 whether you can reach the last position.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: We can jump 1 step first, get 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 of index 3. But the maximum jump length at this position is 0, so you can never reach the last position

 

Idea: Greedy algorithm, each time you find the maximum value of the array value that can be jumped, see if you can jump to the end through this maximum value. Can not jump to the end, choose the largest value to jump. Then repeat the above operation.

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int n = nums.size();
        int rightmost = 0;  //最远可以到达的地方

		//遍历数组
        for (int i = 0; i < n; ++i) {
            if (i <= rightmost) {
				//如果较大值可以到达,则说明可以到达
                rightmost = max(rightmost, i + nums[i]);
                if (rightmost >= n - 1) {
                    return true;
                }
            }
        }
        return false;
    }
};

 

Reference address: https://leetcode-cn.com/problems/jump-game/solution/tiao-yue-you-xi-by-leetcode-solution/

Guess you like

Origin blog.csdn.net/ma2595162349/article/details/108883444