LeetCode 55 _ Jump Game 跳跃游戏

Description:

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.

 

 

Solution: 

这道题让我们计算以数字的值为步数,是否能跳到数组的末位

 

其实这道题挺简单的,不知道为什么是medium?

核心思路就是引入一个变量temp,遍历数组内所有的数,将当前能跳的最长距离存入temp(每次将当前元素能跳的距离与之前最远距离相比,将较远的那个存入)。

如果当前能跳的距离落在最后一个数或其后,表示能跳到,输出true。

但是肯定不是一直将整个数组遍历完的,不能成功跳到数组的末位的情况,如题目描述中的第二种情况,具有什么特点呢?

我们来看题目中的例子 [3,2,1,0,4],当在3位时,之前最远能跳到的地方temp为3,当前位置能跳的距离也为3,判断的条件即为两个情况都该处不能向前跳且之前能跳的距离也不大于此处。

 

 

Code:  

public boolean canJump(int[] nums) {

    int n = nums.length;
    int far = 0;

    for (int i = 0; i < n; i++){
        if (far < i){
            return false;
        }
        far = Math.max(nums[i] + i, far);
        if (far >= n -1){
            return true;
        }
    }
    return true;
}

  

 

 

提交情况:

Runtime: 1 ms, faster than 99.96% of Java online submissions for Jump Game.
Memory Usage: 40.4 MB, less than 43.96% of Java online submissions for Jump Game.

 

 

其他答案:

LeetCode中还有一个答案,它的思路和这个大致一样,但是用了temp作为遍历的指针,写出来更为简洁。代码如下:
public boolean canJump(int[] nums) {
    int i = 0;
    for (int reach = 0; i < nums.length && i <= reach; ++i){
        reach = max(i + nums[i], reach);
        return i == nums.length;
    }
}

  

posted @ 2019-03-29 20:19  Doris7  阅读(114)  评论(0编辑  收藏  举报