您的位置:首页 > 其它

[LeetCode] Jump Game 跳跃游戏

2017-04-23 21:13 369 查看
声明:原题目转载自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 个位置,则同样能到达其后的 num
4000
s[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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: