leetCode #45 Jump Game II 贪心

题目:输出能跳到数组末尾的最小跳数。详见Jump Game

分析:同样,也是贪心。因为当前跳如果能跳到k,那么必然也能跳到小于k的地方,所以贪心是可以的。然后用一个int记录当前跳能到的最大位置,另一个int记录下一跳能到的最大位置,模拟跳的过程:从i=0往前跳,如果当前跳不能到i,而下一跳可以到i,则多跳一步,否则就以i跳更新下一跳的最大距离

答案:

class Solution {
public:
	int jump(vector<int>& nums) {
		int n = nums.size();
		int nextMaxReach = 0;
		int currentMaxReach = 0;
		int jumpCount = 0;
		for (int i = 0; i< n ; i ++){
			if (currentMaxReach >=n -1)// we can reach final
				return jumpCount;

			if (i <= currentMaxReach){// we can reach i
				nextMaxReach = max(i+nums[i], nextMaxReach);//update max reach we can do in next jump
				printf("round: %d update next reach: %d\n",i,nextMaxReach);
			}else{// we can not reach i in this jump
				if (i <= nextMaxReach){// but we can reach i in next jump
					jumpCount++;
					currentMaxReach = nextMaxReach;
					nextMaxReach = max(i+nums[i], nextMaxReach);// jump and update
					printf("round: %d jump: %d\n",i,currentMaxReach);
				}else{
					return -1;// we cannot reach i, never
					printf("round: %d we can not go further\n",i);
				}
			}
			if (nextMaxReach >=n -1)// we can reach final
				return jumpCount+1;
		}
		
		return -1;
	}
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值