[LeetCode] 55. Jumping game (greedy)

topic

Given a non-negative integer array, you initially located in the first position of the array.

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

To determine whether you are able to reach a final position.

Example 1:

Input: [2,3,1,1,4]
Output: true
explanation: we can jump a first step, from the position 0 to the position 1, then jump from step 3 1 reaches the position of the last position.
Example 2:

Enter: [3,2,1,0,4]
output: false
explanations: Either way, you will always reach an index of 3. But the maximum length of the jump position is 0, so you can never reach a final position.

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/jump-game
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

answer

  • In fact,
    if a jump after the element, it will be able to jump to that element. In particular, if we jump behind the last element, it will be able to jump to the last element.
    If the front can reach the most remote point are less than the current, then the current point and the following point is not reachable.

  • Therefore, we iterate, the current point <= maximum current can jump distance, described up to this point, update the maximum distance can jump; if the current point> current can jump to the maximum distance, direct return false .
    Because of the convenience that contains the last point, so if we go to the end, ture is returned.

  • In my opinion, in the maintenance of the current greedy up to the most remote, use it with other comparison.
  • Time complexity of O (n)

Code

class Solution {
    public boolean canJump(int[] nums) {
        int maxDisIdx = 0;
        for (int i = 0; i < nums.length; ++i) {
            if (i > maxDisIdx) {
                return false;
            }
            maxDisIdx = Math.max(maxDisIdx, i + nums[i]);
        }
        return true;
    }
}

Guess you like

Origin www.cnblogs.com/coding-gaga/p/11719423.html