LeetCode#55. 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.

题意:

此问题可以采用队列来解决,应用BFS的思想,创建一个int队列q,一个变量max_num记录最大跳到的距离,初始记为0

例如第一个案例A = [2,3,1,1,4]。

初始队列q 为空,将第一个位置0加入队列中。

nums[0] = 2,该位置可以往后跳两个位置,则将1,2加入到队列中,将0移出队列,更新max_num = 2。

取队首元素1,nums[1]= 3,可以往后跳3个位置,最远可以调到4,4 > max_num, 将2,3,4加入队列中,因为此时2已经在队列中,故不用考虑,因为4即是终点,故该数列可以到达终点。

一种c++的实现方法如下:

#include<iostream>
#include<vector>
#include<queue>
#include<iterator> 
using namespace std;

class Solution {
public:
    bool canJump(vector<int>& nums) {
        queue<int> q;
        int last_index = nums.size()-1;
        if(nums.size() == 0 || nums.size() == 1) return true;
        q.push(0);
        int pos = 0;
        int max_num = 0;
        while(!q.empty()) {
        	int index = nums[pos];
            //如果当前队首所能跳到的最远位置小于目前已到的最远位置,则不用往队列中加入任何位置,因为这些位置已经在队列中
        	if(max_num < pos+index) {
                //将当前队列中最远位置到队首能到达的最远位置加入队列中
        		for(int i = max_num+1; i <= pos+index; i++) {
        			if(i == last_index) {
        				return true;
					}
					if(i > max_num) {
						q.push(i);
					}
				}
			}
            //更新最远位置
			if(max_num <= pos+index) {
				max_num = pos+index;
			}
			q.pop();
			pos = q.front();
		}
		return false;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值