-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0045.cpp
66 lines (61 loc) · 1.41 KB
/
0045.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
/*
// 代码随想录 方法一
int jump(vector<int>& nums)
{
if (nums.size() == 1)
return 0;
// 当前覆盖最远距离下标
int curDistance = 0;
int ans = 0;
// 下一步覆盖最远距离下标
int nextDistance = 0;
for (int i = 0; i < nums.size(); i++)
{
// 更新下一步覆盖最远距离下标
nextDistance = max(i + nums[i], nextDistance);
if (i == curDistance)
{
ans++;
curDistance = nextDistance;
if (nextDistance >= nums.size() - 1)
break;
}
}
return ans;
}
*/
// 代码随想录 方法二
int jump(vector<int>& nums)
{
// 当前覆盖最远距离下标
int curDistance = 0;
int ans = 0;
// 下一步覆盖最远距离下标
int nextDistance = 0;
// 注意这里是i < nums.size()
for (int i = 0; i < nums.size() - 1; i++)
{
// 更新下一步覆盖最远距离下标
nextDistance = max(i + nums[i], nextDistance);
if (i == curDistance)
{
ans++;
curDistance = nextDistance;
}
}
return ans;
}
};
int main()
{
vector<int> nums = { 2,1,1 };
Solution S;
S.jump(nums);
return 0;
}