leetcode 随笔 Jump Game II

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
    Jump 1 step from index 0 to 1, then 3 steps to the last index.

这个题最大的难点对我来说是理解题意。。。。

题意是这样的,就是给你一个数组,你开始在0的位置,然后你跳到哪个位置,哪个位置上的数表示你下一步最多能跳多少格。

比如[2,3,1,1,4],你开始在位置0,位置0上的数字是2,你最多可以跳两格,也就是说可以跳到位置1和位置2,位置1位置2上的数字分别是3和1,如果你跳到位置1,那么下一步你最多跳3步就直接到终点了。

问题是求最短的跳数。

这个题基本上看懂了就能看出来其实跳数和位置之间是有包含关系的,比如位置1上的3,包含了,位置2上的1,所以下一步要跳也得跳位置1,然后每次求最佳的跳位即可。

runtime 13ms

class Solution {
public:
	int jump(vector<int>& nums) {
		if (nums.empty()||nums[0]==0||nums.size()==1) return 0;
		int size = nums.size();
		int count = 0;
		int index = 0;
		if (nums[0] >= size - 1)return 1;
		while (index != size - 1)
		{
			count++;			
			if (nums[index] + index >= size - 1) return count;
			int record = nums[index + 1] + index + 1, next_index = index + 1;
			for (int i = 0; i < nums[index]-1; i++)
			{
				if (index + i + 2 + nums[index + i + 2] >= record)
				{
					record = index + i + 2 + nums[index + i + 2];
					next_index = index + i + 2;
				}
			}
			if (next_index == record) return 0;
			index = next_index;
		}
		return count;
	}
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值