[LeetCode 55] 跳跃游戏

题面:

在这里插入图片描述

数据范围:

1 ≤ n u m s . l e n g t h ≤ 1 0 4 1 \le nums.length \le 10^4 1nums.length104
0 ≤ n u m s [ i ] ≤ 1 0 5 0 \le nums[i] \le 10^5 0nums[i]105

思路:

贪心记录最大能跳到的下标就行了,假设用 m a x P o s maxPos maxPos 记录。

  1. 如果当前的 i n d e x > m a x P o s index > maxPos index>maxPos,则说明当前已经跳不到 i n d e x index index 了,那么 i n d e x index index 及之后的数据对结果都不会有贡献,也就是说包跳不动 n − 1 n-1 n1 这个终点的,直接返回 f a l s e false false.
  2. 否则说明当前这一步是可以跳到 i n d e x index index 的,那么尝试更新 m a x P o s maxPos maxPos,及 m a x P o s = m a x ( m a x P o s , i n d e x + n u m s [ i n d e x ] ) maxPos = max(maxPos, index + nums[index]) maxPos=max(maxPos,index+nums[index])
  3. 只要有一次 m a x P o s ≥ n − 1 maxPos \ge n-1 maxPosn1,即可 r e t u r n    t r u e return \ \ true return  true

代码:

bool canJump(vector<int>& nums) {
     int n = nums.size();
     if(nums[0] >= n) return true;
     if(nums[0] == 0 && n > 1) return false;
     int maxPos = 0;
     for(int i = 0; i < n; ++i) {
         if(i > maxPos) return false;
         maxPos = max(maxPos, i + nums[i]);
         if(maxPos >= n - 1) return true;
     }
     return false;
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值