mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
add 45. Jump Game II 🍺
This commit is contained in:
parent
b19667ff1b
commit
8b35120ef4
@ -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| |
|
||||
|
52
solutions/45. Jump Game II.md
Normal file
52
solutions/45. Jump Game II.md
Normal file
@ -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<int>& 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<int>& 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;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user