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.

 

和之前的Jump Game II相似,只是这次是判断是否可以到达;

采用相同的思路,具体见Jump Game II,

当两步之间可以到达的最远距离不变时(且没有超过终点),说明终点无法到达。

 

代码:

class Solution {
public:
    bool canJump(int A[], int n) {
		int last_end=-1,end=0;	//上一步结束时可到达的最远位置,当前步可到达的最远位置
		int i,temp;
		while(end<n-1)
		{
			temp=end;
			for(i=last_end+1;i<=end;i++)
				if(i+A[i]>temp)
					temp=i+A[i];
			last_end=end;
			end=temp;
			if(end==last_end)
				break;
		}
		if(end>=n-1)
			return true;
		else
			return false;
    }
};


 

 

 

 

 

你可能感兴趣的:(LeetCode,C++,算法)