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;
    }
};



猜你喜欢

转载自blog.csdn.net/zc2985716963/article/details/78924428