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.
每次计算最远能走到的位置,时间复杂度\(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; } } };