題目描述:給定一個非負整數數組,你最初位於數組的第一個位置。java
數組中的每一個元素表明你在該位置能夠跳躍的最大長度。segmentfault
你的目標是使用最少的跳躍次數到達數組的最後一個位置。數組
假設你老是能夠到達數組的最後一個位置。網絡
示例說明請見LeetCode官網。url
來源:力扣(LeetCode)
連接:https://leetcode-cn.com/probl...
著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。code
- 首先,若是nums的長度爲1,由於不須要走,直接返回0;
- 若是nums的長度爲2,因爲必定能夠到達最後一個位置,並且至少須要一步,直接返回1;
當不是前兩種狀況時,首先,聲明一個變量length爲數組最大的索引位,聲明一個變量result記錄最少的跳躍次數,初始化爲最大的的int值,聲明一個HashMap爲toJumpTimes記錄跳躍過的位置和相應跳躍到該位置最少的步數,聲明一個隊列toJump記錄當前走到的位置,聲明一個隊列times同步記錄走到當前位置須要的步數,首先,將0加入到jumped和times,而後遍歷隊列toJump按照如下過程處理:索引
- 從隊列中取出一位cur;
- 若是cur對應的數組的值爲0,則跳過處理下一個隊列中的值;
- 判斷toJumpTimes中是否存在該位置的索引,若是存在且走到當前位置的步數多於其餘走法走到當前位置的步數,則跳過處理下一個;
- 若是cur對應的數組的值大於等於
length-cur
便可以從當前位置直接跳躍到最後一位,則判斷若是當前的跳躍次數小於result,則更新result的值;不然,若是當前跳躍次數不小於result,則跳過處理下一個;若是當前跳躍次數小於result,則將
cur+1 ~ cur+nums[cur]
索引位添加到toJump,添加以前須要判斷toJumpTimes的key中是否存在當前索引位:隊列
- 若是不存在而且當前跳躍次數小於result,則把當前索引位和相應的跳躍次數添加到toJump和times和toJumpTimes;
- 若是存在而且當前跳躍次數小於最小的跳躍次數,則把當前索引位和相應的跳躍次數添加到toJump和times,而且更新當前索引位在toJumpTimes中的最少跳躍次數。
最後,返回result即爲最少跳躍次數。遊戲
說明:處理方法相似於 LeetCode-055-跳躍遊戲 這道題目。leetcode
import java.util.*; public class LeetCode_045 { public static int jump(int[] nums) { if (nums.length == 1) { return 0; } if (nums.length == 2) { return 1; } int result = Integer.MAX_VALUE; int length = nums.length - 1; // 定義走到過的位置,而且記錄走到當前位置最少的步數 Map<Integer, Integer> toJumpTimes = new HashMap<>(); toJumpTimes.put(0, 0); // 定義當前到的位置 Stack<Integer> toJump = new Stack<>(); Stack<Integer> times = new Stack<>(); toJump.push(0); times.push(0); while (!toJump.isEmpty()) { Integer cur = toJump.pop(); Integer curTimes = toJumpTimes.get(cur); if (nums[cur] == 0) { continue; } // 判重,若是走到當前位置的步數多於其餘走法走到當前位置的步數,則跳過處理下一個 if (toJumpTimes.containsKey(cur) && curTimes > toJumpTimes.get(cur)) { continue; } if (nums[cur] >= length - cur) { if (curTimes + 1 < result) { result = curTimes + 1; } } else { if (curTimes + 1 >= result) { continue; } for (int i = 1; i <= nums[cur]; i++) { if (!toJumpTimes.containsKey(cur + i)) { if (curTimes + 1 < result) { toJumpTimes.put(cur + i, curTimes + 1); toJump.push(cur + i); times.push(curTimes + 1); } } else { Integer time = toJumpTimes.get(cur + i); if (curTimes + 1 < time) { toJumpTimes.put(cur + i, curTimes + 1); toJump.push(cur + i); times.push(curTimes + 1); } } } } } return result; } public static void main(String[] args) { int[] nums = new int[]{2, 3, 1, 1, 4}; System.out.println(jump(nums)); } }
【每日寄語】 要銘記在心:天天都是一年中最美好的日子。