题目
解答
#include <iostream>
#include <string>
#include <list>
#include <vector>
#include <map>
#include <utility>
#include <functional>
#include <algorithm>
#include <cassert>
bool canJump(const std
::vector
<int>& nums
) {
if (nums
.size() <= 1) {
return true;
}
std
::vector
<int> distances
;
for (int i
= 0; i
< nums
.size(); ++i
) {
int distance
= i
+ nums
[i
];
distances
.push_back(distance
);
}
int max_distance
= distances
[0];
for (int i
= 1; i
< nums
.size(); ++i
) {
if (max_distance
>= nums
.size() - 1) {
return true;
}
if (max_distance
< i
) {
return false;
}
if (max_distance
< distances
[i
]) {
max_distance
= distances
[i
];
}
}
return true;
}
int main() {
std
::cout
<< (canJump({ 2, 3, 1, 1, 4 }) ? "Can" : "No") << std
::endl
;
std
::cout
<< (canJump({ 3, 2, 1, 0, 4 }) ? "Can" : "No") << std
::endl
;
return 0;
}
转载请注明原文地址:https://tech.qufami.com/read-19421.html