-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcanJump.cpp
More file actions
30 lines (27 loc) · 842 Bytes
/
canJump.cpp
File metadata and controls
30 lines (27 loc) · 842 Bytes
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
#include <vector>
using namespace std;
class Solution {
public:
bool canJump(vector<int>& nums) {
if (nums.empty()) return false;
int lastIdx = nums.size() - 1;
// 能跳到的最远的下标所在索引
int currentCanJumpMaxIdx = 0;
// i: 下标
for (int i = 0;i < lastIdx;i++)
{
currentCanJumpMaxIdx = max(currentCanJumpMaxIdx,i + nums[i]);
// 如果超过了当前可达的最大可跳跃索引,那说明后续就到不了了,直接返回false
if (i >= currentCanJumpMaxIdx) return false;
}
if (currentCanJumpMaxIdx >= lastIdx) return true;
return false;
}
private:
template<typename T>
static inline T max(T num1,T num2)
{
if (num1 > num2) return num1;
else return num2;
}
};