leetcode_55题——Jump Game(贪心算法)

Jump Game

 Total Accepted: 43051 Total Submissions: 158263My Submissions

 

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.

 

Hide Tags
 Array Greedy
Have you met this question in a real interview? 
Yes
 
    这道题目的意思是问你能否从A【0】跳到A【end】,每一个值是在该处所能跳跃的步数的最大值,
    1.我想采用广度优先搜索的方法来做,利用队列将A[i]的位置i压入之后,将之后从i+1到i+A[i]的的位置都压进去,再在头处将i出来,并将i放进set中,之后不要再压i了
结果发现这种广度优先搜索的方法还是超出时间限制了
#include<iostream>
#include<set>
#include<queue>
using namespace std;

bool canJump(vector<int>& nums) {
	if(nums.empty())
		return false;
	if(nums[0]==0)
		return false;
	set<int> temp_set;
	queue<int> temp_queue;
	temp_queue.push(0);
	temp_set.insert(0);

	int len=nums.size();

	while(!temp_queue.empty())
	{
		int temp_int=temp_queue.front();
		temp_queue.pop();
		for (int i=0;i<=nums[temp_int];i++)
		{
			int next_location=temp_int+i;
			if(next_location==len-1)
				return true;
			if(next_location<len-1)
			{
				if(temp_set.count(next_location)==0)
				{
					temp_set.insert(next_location);
					temp_queue.push(next_location);
				}
			}
		}
	}
	return false;
}
int main()
{
	vector<int> vec;
	vec.push_back(3);vec.push_back(2);vec.push_back(1);vec.push_back(0);vec.push_back(4);
	cout<<canJump(vec)<<endl;
}

  2. 所以呢我又想到另外一种方法,应该是类似于贪心算法,先将A【i】所跳的最大位置找到,再从这个位置依次往A【i+1】处遍历,在这期间找到第二个最大的位置

再重复刚才的过程,在这个中间可以判断是否能够跳到最后。

#include<iostream>
#include<set>
#include<queue>
using namespace std;

bool canJump(vector<int>& nums) {
	if(nums.empty())
		return false;
	if(nums.size()==1)
		return true;
	if(nums[0]==0)
		return false;
	int len_nums=nums.size();
	int max_location=nums[0]+0;
	if(max_location>=len_nums-1)
		return true;
	int max_location0=0;

	while(1)
	{
		int temp_max=0;
		for(int i=max_location;i>max_location0;i--)
		{
			if(nums[i]+i>=len_nums-1)
				return true;
			if(nums[i]+i>temp_max)
				temp_max=nums[i]+i;
		}
		if(temp_max<max_location)
			return false;

		max_location0=max_location;
		max_location=temp_max;
	}
}
int main()
{
	vector<int> vec;
	vec.push_back(3);vec.push_back(2);vec.push_back(1);vec.push_back(0);vec.push_back(4);
	cout<<canJump(vec)<<endl;
}

  

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。