1. 程式人生 > >LeetCode:55. Jump Game(跳遠比賽)

LeetCode:55. Jump Game(跳遠比賽)

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: [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: [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.

方法1:

package leetcode;

import org.junit.Test;

/**
 * @author zhangyu
 * @version V1.0
 * @ClassName: JumpGame
 * @Description: TOTO
 * @date 2018/12/13 16:26
 **/


public class JumpGame {
    @Test
    public void fun() {
        int[] nums = {2, 3, 1, 1, 4};
        boolean flag = canJump2(nums);
        System.out.println(flag);
    }
    
    public boolean canJump2(int[] nums) {
        int n = nums.length;
        int range = 0;
        for (int i = 1; i <= n; i++) {
            range = Math.max(range - 1, nums[i - 1]);
            if (range == 0 && i < n)
                return false;
            if (range > n - 1)
                return true;
        }
        return true;
    }

    private boolean jumpGame(int[] nums) {
        int max = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i - 1] == 0 && i > max + nums[max]) {
                return false;
            }
            //max = nums[i] > nums[max] - (i - max) ? i : max;
            if (nums[i] > nums[max] - (i - max)) {
                max = i;
            }
        }
        return true;
    }
}

時間複雜度:O(n)

空間複雜度:O(1)