当前位置:网站首页>Jump game of leetcode topic analysis

Jump game of leetcode topic analysis

2022-06-23 09:36:00 ruochen

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.

For example:

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

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

Set variables maxStep Is the maximum number of steps that you can jump , Over array length , It means you can jump out ; Otherwise, you can't jump out .

that maxStep How to find out ?numsi + i On behalf of : Jump from current position , The farthest position you can jump .

    public boolean canJump(int[] nums) {
        if (nums == null || nums.length == 0) {
            return false;
        }
        int maxStep = 0;
        for (int i = 0; i < nums.length; i++) {
            if (maxStep >= nums.length - 1) {
                return true;
            }
            if (nums[i] == 0 && maxStep == i) {
                return false;
            }
            maxStep = Math.max(maxStep, nums[i] + i);
        }
        return true;
    }
原网站

版权声明
本文为[ruochen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/01/202201081604220757.html