标签:地方 判断 整数 turn 输出 索引 can har csharp
https://leetcode-cn.com/problems/jump-game/
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个位置。
示例 1:
输入: [2,3,1,1,4]
输出: true
解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。
示例 2:
输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。
贪心: 贪的是,跳到下个位置,该位置 能跳到最远。
class Solution {
public:
//贪心:找当前位置要跳哪,实际上,当前位置要跳到 下一个能跳到更远位置的那个地方
//比如 nums[i] 能到 i+1 ... j 找index+nums[index]最大的即可。
bool canJump(vector<int>& nums) {
int max_index = 0,i=0;
for(i=0;i<nums.size();i++){
if(i > max_index){
return false;
}
if(max_index >= nums.size()-1){
return true;
}
max_index = max(nums[i] + i,max_index);
}
return true;
}
};
标签:地方 判断 整数 turn 输出 索引 can har csharp
原文地址:https://www.cnblogs.com/wsw-seu/p/13194112.html