標籤:leetcode java 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.)
題意:
給定一個非負整數數組,給定的初始化位置在數組的起始位置。
數組中的每個元素代表著你能都在此位置跳躍的最大的距離。
你的目標是用最少的跳躍數達到數組的末尾。
比如:給定A = [2,3,1,1,4]
達到數組尾部的最小的跳躍步數為2。(用1步從索引 0 到 1, 接著用3步到達結尾索引。)
演算法分析:
該題思想主要是,掃描數組,以確定當前最遠能覆蓋的節點,放入maxreach。然後繼續掃描,直到當前的路程超過了上一次算出的覆蓋範圍reach,那麼更新覆蓋範圍,同時更新條數,因為我們是經過了多一跳才能繼續前進的。
形象地說,這個是在爭取每跳最遠的greedy.
* ret:目前為止的jump數
* curRch:從A[0]進行ret次jump之後達到的最大範圍
* curMax:從0~i這i+1個A元素中能達到的最大範圍
* 當curRch < i,說明ret次jump已經不足以覆蓋當前第i個元素,因此需要增加一次jump,使之達到
* 記錄的curMax。
AC代碼:
/** * ret:目前為止的jump數 * curRch:從A[0]進行ret次jump之後達到的最大範圍 * curMax:從0~i這i+1個A元素中能達到的最大範圍 * 當curRch < i,說明ret次jump已經不足以覆蓋當前第i個元素,因此需要增加一次jump,使之達到 * 記錄的curMax。 */ public class Solution {public int jump(int[] nums) { int ret = 0; int curMax = 0; int curRch = 0; for(int i = 0; i < nums.length; i ++) { if(curRch < i) { ret ++; curRch = curMax; } curMax = Math.max(curMax, nums[i]+i); } return ret; } }
著作權聲明:本文為博主原創文章,轉載註明出處
[LeetCode][Java] Jump Game II