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.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
一開始考慮用動態規劃,當前位置i是否可以到達可以轉化為,[0,...,i-1]區間的位置可以到達且該位置step大于與i的index差值,用一個boolean數組dp[]來存儲之前的狀態,然而寫完就LTE了。。。不開心。。。因為每次判斷都需要用到之前所有狀態,太耗時了。
改進:用maxCover記錄最大可到達距離,step記錄仍然可走的步數,遍歷數組更新這兩個值,若step=0且沒有走到數組尾部,則返回false;若遍歷完成則返回true,這樣只用掃描一遍且每一步都不需要再掃描之前每一步的狀態。
原因是每次只用記錄當前可以走到最大距離的那個狀態!!!
代碼:
public class Solution {
public boolean canJump(int[] nums) {
if (nums.length == 0) return false;
int maxCover = 0, step = 1;
for (int i = 0; i < nums.length; i++) {
step--;
if (i + nums[i] > maxCover) {
maxCover = i + nums[i];
step = nums[i];
}
if (step == 0 && i < nums.length-1) return false;
}
return true;
}
}
45 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.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
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.)
Note:You can assume that you can always reach the last index.
關鍵的問題1:到底什么時候總步數+1呢?
回答:假設到遍歷到數組index=i的位置,在此之前jump到的位置為k;在位置k最遠可以到達的范圍是[k,reach],如果reach<i,說明[k-reach]之間必須再jump一次,這樣才能保證i在可以reach的范圍內!
關鍵問題2:那究竟在[k-reach]的哪個位置再次jump呢?
回答:根據貪心算法,應該挑可以reach范圍最遠的那個點,如果需要求jump game的最短次數的jump路徑,就需要記錄這個點了。
本題僅解決問題1即可。
public class Solution {
public int jump(int[] nums) {
if (nums.length <= 1) return 0;
int reach = nums[0];
int lastreach = 0;
int step = 0;
for (int i = 1; i <= reach && i < nums.length; i++) {
if (i > lastreach) {
step++;
lastreach = reach;
}
reach = Math.max(reach, i+nums[i]);
}
if (reach < nums.length-1) return 0;
return step;
}
}