【LeetCode】45. 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.

Note:

You can assume that you can always reach the last index.

 

描述:

给出一个整形数组,每个元素代表在这个位置处能跳的最大距离,起始位置在下标0处,问最少多少次能跳到最后一个位置。

 

分析:

可以采用DP,

times[i] 表示跳到第 i 个位置最少需要的次数,times[0] = 0,其他元素均为nums的长度len(题目中说有解,那每次至少跳一步,因此最多需要跳len次) 

在每个位置i,对于所能跳到的所有的位置 j (j属于 [i + 1, i + nums[i] ] 且 小于 len),均尝试更新缩小times[i + j],直到程序终止。

以上DP算法需要两层循环,n^2 的复杂度,会出现超时,需要优化

 

考虑贪心的思路,每一次在跳之前,都选择能跳到的位置中预期能跳更远位置的位置,这句话有点绕,下面解释一下

对于本题来说,目标是最快跳到终点,所以在每次跳跃前,都选择当前能跳到的位置中,后续能跳到更远位置的那个地方,这样每一步操作下去,能达到全局最优。

说的可能不太明白,还是上代码吧!

 

几组数据:

[5,2,1]
[2,3,1,1,4,2,3,1,1,4]
[1]
[1,1]
[1,1,1,1,1,1]
[2,3,1,1,4]
[2,2,1,1,4]
[2,2,1]

 

代码一:(时间复杂度O (n^2),超时)

class Solution {
public:
	int jump(vector<int>& nums) {
		int len = nums.size();
		vector<int> times(len, len);
		times[0] = 0;
		for (int i = 0; i < len; ++ i) {			
			for (int j = 1; j <= nums[i]; ++ j) {
				int index = i + j;
				if (index < len) {
					times[index] = min(times[index], times[i] + 1);
				}
			}
		}
		return times[len - 1];
    }
};

 

代码二:(时间复杂度 O(n))

class Solution {
public:
	int jump(vector<int>& nums) {
		int len = nums.size(), start = 0, new_start = 0, result = 0;
		for (int i = 1; i < len; ++ i) {
			if (new_start + nums[new_start] < i + nums[i]) {
				new_start = i;
			}

			if (i - start == nums[start] || i == len - 1) {
				start = new_start;
				++ result;
			}
		}
		return result;
	}
};

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值