From 8b35120ef45f817a6fc4f54ce7fe6a5978074d25 Mon Sep 17 00:00:00 2001 From: ShusenTang Date: Fri, 3 Apr 2020 22:05:41 +0800 Subject: [PATCH] add 45. Jump Game II :beer: --- README.md | 1 + solutions/45. Jump Game II.md | 52 +++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 solutions/45. Jump Game II.md diff --git a/README.md b/README.md index f0c0d6c..a6db914 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ My LeetCode solutions with Chinese explanation. 我的LeetCode中文题解。 | 42 |[Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/)|[C++](solutions/42.%20Trapping%20Rain%20Water.md)|Hard| | | 43 |[Multiply Strings](https://leetcode.com/problems/multiply-strings/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/43.%20Multiply%20Strings.md)|Medium| | | 44 |[Wildcard Matching](https://leetcode.com/problems/wildcard-matching/)|[C++](solutions/44.%20Wildcard%20Matching.md)|Hard| | +| 45 |[Jump Game II](https://leetcode.com/problems/jump-game-ii/) |[C++](solutions/45.%20Jump%20Game%20II.md)|Hard| | | 46 |[Permutations](https://leetcode.com/problems/permutations/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/46.%20Permutations.md)|Medium| | | 47 |[Permutations II](https://leetcode.com/problems/permutations-ii/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/47.%20Permutations%20II.md)|Medium| | | 48 |[Rotate Image](https://leetcode.com/problems/rotate-image/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/48.%20Rotate%20Image.md)|Medium| | diff --git a/solutions/45. Jump Game II.md b/solutions/45. Jump Game II.md new file mode 100644 index 0000000..ee0b338 --- /dev/null +++ b/solutions/45. Jump Game II.md @@ -0,0 +1,52 @@ +# [45. Jump Game II](https://leetcode.com/problems/jump-game-ii/) + +# 思路 + +跳格游戏,问最少跳多少步可跳到最后一个格子。 + +因为我们需要用最少的步数跳到最后一个格子,所以可以考虑用贪心的思想,不过这里贪婪并不是每次都要跳到最远的格子,而是贪婪地求出用一定步数所能跳出最远的范围,一旦当这个范围到达末尾时,此时所用的步数一定是最小步数。所以基本思想是假设我们求出了用`step - 1`步能跳到的最远格子,那么就可以求出用`step`能跳到的最远范围。 + +为此,先定义记录步数的变量`step`,再定义两个变量`cur`和`pre`分别来保存当前的能到达的最远位置和之前能到达的最远位置,然后从后往前遍历 +* 如果当前位置`i`小于等于pre,说明还是在`step`步能到达的范围内,根据当前位置格子的值来更新`cur`:`cur = max(cur, i + nums[i])`; +* 如果当前位置`i`等于了pre,说明到达了`step`步能到达的范围内的最后一个格子,所以此时我们需要更新`pre`为`cur`,然后将step加1。 + +时间复杂度O(n),空间复杂度O(1) + +# C++ +## 写法一 +``` C++ +class Solution { +public: + int jump(vector& nums) { + int n = nums.size(), i = 0, cur = 0, pre = 0, step = 0; + for(int i = 0; i < n - 1; i++){ + cur = max(cur, i + nums[i]); + if(i == pre){ + pre = cur; + step++; + if(cur >= n - 1) return step; + } + } + return step; + } +}; +``` + +## 写法二 +``` C++ +class Solution { +public: + int jump(vector& nums) { + int n = nums.size(), i = 0, cur = 0, pre = 0, step = 0; + while(cur < n - 1){ + while(cur < n - 1 && i <= pre) + cur = max(cur, i + nums[i++]); + pre = cur; + step++; + } + return step; + } +}; +``` + +