链接
LeetCode题目:https://leetcode.com/problems/jump-game/
难度:Medium
题目
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
分析
因为这个数列的数字都是非负整数,为了保证能从起点到终点,只需要“避开”跳跃距离是0的点。
具体做法是用贪心算法,用一个值记录当前能到达的最远距离,遍历一遍整个数列,遇到跳跃距离是0的点则判断最远距离是否更远,否则更新最远距离。
代码
class Solution {
public:
bool canJump(vector<int> &nums) {
if (nums.size() == 1) return true;
int max_dis = nums[0];
bool ans = true;
for (int i = 0; i < nums.size() - 1; i++) {
if (nums[i] == 0) {
if (max_dis <= i) {
ans = false;
break;
}
} else {
max_dis = max(max_dis, i + nums[i]);
}
}
return ans;
}
};