【Leetcode】之 Jump Game

一.问题描述

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.

Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

二.我的解题思路

拿到这道题,最直接的思路就是去遍历,但是很显然,这种做法的时间复杂度很高。

接下来就去思考能否使用经典的算法思想去做,比如回溯法,贪心算法等等。那么针对这道题,直观的感觉是可以采用贪心算法。

采用贪心算法的关键是选取合适的贪心策略。如果在某个位置,其能到达的最远距离超过last index,而从起点也是可以到达该位置的,那么就应该返回true。

因此,在遍历数组的时候维护一个max_step变量,表示当前位置可以到达的最远距离。测试通过的程序如下:

class Solution {
public:
	bool canJump(vector<int>& nums) {
		int len = nums.size();
		if (len == 0) return false;
		if (len == 1) return true;
		int max_step = nums[0];
		for (int i = 1; i<len - 1; i++){
		
			if (max_step == 0) return false;
		    	max_step--;
			if (nums[i] >max_step) max_step = nums[i] ;
			if (i+max_step >= len - 1) return true;


		}
		if(max_step<len-1)
		    return false;
		else
		    return true;
	}
};


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值