[LeetCode] Jump Game 跳跃游戏

声明:原题目转载自LeetCode,解答部分为原创

Problem:

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.

Solution:

思路一:最直接的想法,遍历一遍数组nums[] ,假如能够到达数组中第 i 个位置,则同样能到达其后的 nums[i] 个位置,最终只需判断能到达的位置中有没有包含最后一个位置即可。该办法思路简单,容易实现,但时间复杂度为O( n ^ 2 )

代码如下:

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

class Solution {
public:
    bool canJump(vector<int>& nums) {
        vector<int> route(nums.size());
        //initial
        assign_value(route, 0, nums.size(), 0);
        route[0] = 1;
        
        for(int i = 0 ; i < nums.size() ; i ++)
        {
        	if(route[i] == 1)
        	{
        		if(nums[i] > 0)
        		{
        			assign_value(route, i + 1 , i + 1 + nums[i], 1);
				}
			}
			else
				break;
		}
		
		return route[route.size() - 1];
    }
    
private:
	void assign_value(vector<int> & temp, int begin, int end, int value)
	{
		for(int i = begin; i < end; i ++)
		{
			temp[i] = value;
		}
	}
};

int main()
{
	vector<int> nums(5);
	nums[0] = 2;nums[1] = 3;nums[2] = 1;nums[3] = 1;nums[4] = 4;
	
	Solution text_1;
	if(text_1.canJump(nums))
		cout << "True" << endl;
	else
		cout << "False" << endl;
	
	nums[3] = 0;
	if(text_1.canJump(nums))
		cout << "True" << endl;
	else
		cout << "False" << endl;
	
	nums[1] = 2;
	if(text_1.canJump(nums))
		cout << "True" << endl;
	else
		cout << "False" << endl;
	
	return 0;
}
思路二:优化算法,以达到线性时间复杂度。便历一遍数组,对于每个可达到的每个位置 i, 只获得下一个可到达的最远点。最终判断最远点是否超过终点,若超过,则可到达终点。
代码如下:

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

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

int main()
{
	vector<int> nums(5);
	nums[0] = 2;nums[1] = 3;nums[2] = 1;nums[3] = 1;nums[4] = 4;
	
	Solution text_1;
	if(text_1.canJump(nums))
		cout << "True" << endl;
	else
		cout << "False" << endl;
	
	nums[3] = 0;
	if(text_1.canJump(nums))
		cout << "True" << endl;
	else
		cout << "False" << endl;
	
	nums[1] = 2;
	if(text_1.canJump(nums))
		cout << "True" << endl;
	else
		cout << "False" << endl;
	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值