LeetCode 55 Jump Game 贪心
作者:互联网
You are given an integer array nums
. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.
Return true
if you can reach the last index, or false
otherwise.
Solution
每次计算最远能走到的位置,时间复杂度\(O(n)\)
点击查看代码
class Solution {
public:
bool canJump(vector<int>& nums) {
int n = nums.size();
if(n==1)return true;
else{
int max_reach=0;
for(int i=0;i<n;i++){
if(i>max_reach)return false;
max_reach = max(max_reach,i+nums[i]);
}
return true;
}
}
};
标签:return,nums,55,max,reach,Jump,int,Game,array 来源: https://www.cnblogs.com/xinyu04/p/16212071.html