Skip to content

Commit 0c96f83

Browse files
committed
feat: add jump game ii
1 parent 47a7886 commit 0c96f83

File tree

4 files changed

+98
-1
lines changed

4 files changed

+98
-1
lines changed

leetcode/greedy_algorithm/jump_game.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
* @Author: Chacha
33
* @Date: 2022-04-25 16:10:12
44
* @Last Modified by: Chacha
5-
* @Last Modified time: 2022-04-25 16:40:37
5+
* @Last Modified time: 2022-05-07 12:51:33
66
*/
77

88
/**
61.6 KB
Binary file not shown.
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
/*
2+
* @Author: Chacha
3+
* @Date: 2022-05-07 11:47:52
4+
* @Last Modified by: Chacha
5+
* @Last Modified time: 2022-05-07 16:06:32
6+
*/
7+
8+
/**
9+
* 来源:https://leetcode-cn.com/problems/jump-game-ii/
10+
*
11+
* 45. 跳跃游戏 II
12+
*
13+
* 给你一个非负整数数组 nums ,你最初位于数组的第一个位置。数组中的每个元素代表你在该位置可以跳跃的最大长度。
14+
* 你的目标是使用最少的跳跃次数到达数组的最后一个位置。假设你总是可以到达数组的最后一个位置。
15+
*
16+
* 示例 1:
17+
* 输入: nums = [2,3,1,1,4]
18+
* 输出: 2
19+
* 解释: 跳到最后一个位置的最小跳跃数是 2。从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
20+
*
21+
* 示例 2:
22+
* 输入: nums = [2,3,0,1,4]
23+
* 输出: 2
24+
*
25+
*/
26+
27+
#include <iostream>
28+
#include <vector>
29+
30+
using namespace std;
31+
32+
class Solution
33+
{
34+
private:
35+
/* data */
36+
public:
37+
int jump(vector<int> &nums);
38+
};
39+
40+
/**
41+
* 方法:贪心算法,正向查找可到达的最大位置
42+
*
43+
* 思路:如果我们「贪心」地进行正向查找,每次找到可到达的最远位置,就可以在线性时间内得到最少的跳跃次数。
44+
*
45+
* 例如,对于数组 [2,3,1,2,4,2,3],初始位置是下标 0,从下标 0 出发,最远可到达下标 2。
46+
* 下标 0 可到达的位置中,下标 1 的值是 3,从下标 1 出发可以达到更远的位置,因此第一步到达下标 1。
47+
* 从下标 1 出发,最远可到达下标 4。下标 1 可到达的位置中,下标 4 的值是 4 ,从下标 4 出发可以达到更远的位置,因此第二步到达下标 4。
48+
*
49+
* 如图 ./jump_game_ii.png
50+
*
51+
* 在具体的实现中,我们维护当前能够到达的最大下标位置,记为边界。我们从左到右遍历数组,到达边界时,更新边界并将跳跃次数增加 1。
52+
*
53+
* 在遍历数组时,我们不访问最后一个元素,这是因为在访问最后一个元素之前,我们的边界一定大于等于最后一个位置,
54+
* 否则就无法跳到最后一个位置了。如果访问最后一个元素,在边界正好为最后一个位置的情况下,
55+
* 我们会增加一次「不必要的跳跃次数」,因此我们不必访问最后一个元素。
56+
*
57+
* 时间复杂度:O(n),其中 n 是数组长度。
58+
* 空间复杂度:O(1)。
59+
*
60+
* 题解:https://leetcode-cn.com/problems/jump-game-ii/solution/tiao-yue-you-xi-ii-by-leetcode-solution/
61+
*
62+
*/
63+
int Solution::jump(vector<int> &nums)
64+
{
65+
int maxPos = 0; // 目前能跳到的最远位置
66+
int n = nums.size(); // 数组长度
67+
int step = 0; // 跳跃次数
68+
int end = 0; // 上次跳跃可达范围右边界(下次的最右起跳点)
69+
70+
for (int i = 0; i < n - 1; i++)
71+
{
72+
if (maxPos >= i)
73+
{
74+
maxPos = max(maxPos, i + nums[i]);
75+
76+
if (i == end)
77+
{
78+
end = maxPos;
79+
step++;
80+
}
81+
}
82+
}
83+
84+
return step;
85+
};
86+
87+
int main(int argc, char const *argv[])
88+
{
89+
Solution s;
90+
vector<int> nums = {2, 3, 1, 2, 4, 2, 3};
91+
vector<int> nums1 = {2, 3, 1, 1, 4};
92+
93+
cout << "nums = [2, 3, 1, 2, 4, 2, 3], 最少的跳跃次数为: " << s.jump(nums) << endl;
94+
cout << "\nnums = [2, 3, 1, 1, 4], 最少的跳跃次数为: " << s.jump(nums1) << endl;
95+
96+
return 0;
97+
}
115 KB
Loading

0 commit comments

Comments
 (0)