[Leetcode] Jump Game 跳躍遊戲

Jump Game I

最新解法請見:https://yanjia.me/zh/2019/01/...

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.code

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

貪心法

複雜度

時間 O(N) 空間 O(1)leetcode

思路

若是隻是判斷可否跳到終點,咱們只要在遍歷數組的過程當中,更新每一個點能跳到最遠的範圍就好了,若是最後這個範圍大於等於終點,就是能夠跳到。get

代碼

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

Jump Game II

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.it

Your goal is to reach the last index in the minimum number of jumps.io

For example: Given array A = [2,3,1,1,4]ast

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)class

雙指針法

複雜度

時間 O(N) 空間 O(1)

思路

若是要計算最短的步數,就不能貪心每次都找最遠距離了,由於有可能一開始跳的遠的路徑,後面反而更慢。因此咱們要探索全部的可能性,這裏用快慢指針分出一塊當前結點能跳的一塊區域,而後再對這塊區域遍歷,找出這塊區域能跳到的下一塊區域的上下邊界,每塊區域都對應一步,直到上界超過終點時爲之。

代碼

public class Solution {
    public int jump(int[] nums) {
        int high = 0, low = 0, preHigh = 0, step = 0;
        while(high < nums.length - 1){
            step++;
            //記錄下當前區域的上界,以便待會更新下一個區域的上界
            preHigh = high;
            for(int i = low; i <= preHigh; i++){
                //更新下一個區域的上界
                high = Math.max(high, i + nums[i]);
            }
            //更新下一個區域的下界
            low = preHigh + 1;
        }
        return step;
    }
}

後續 Follow Up

Q:若是要求返回最短跳躍路徑,如何實現?A:能夠使用DFS,並根據一個全局最短步數維護一個全局最短路徑,當搜索完全部可能後返回這個全局最短路徑。

相關文章
相關標籤/搜索