您的位置:首页 > 理论基础 > 数据结构算法

LeetCode JumpGame and JumpGame II

2017-05-19 11:38 393 查看
大家好,今天给大家带来的是一个贪心算法的题目

先来看下题目描述

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.

说给你个数组你,每个数组里的值代表你能挑多少,问你最后可不可以跳(笑)到最后
拿到题目可以发现这题实际上就是希望我们求每个值能给我们带来的最大收益,

我们希望每一步跳的期望是最高的

假设我们在A【0】点我们可以跳2步,那么我们接下来应该分析后面两步我们跳哪里能够得到最大期望

这里注意不一定是后面2个中数字大的因为跳跃的收益是递增的(怎么理解假设A【1】=2,A【2】=2,我们应该跳到A【2】)

为什么呢,因为我们从A【1】跳到A【2】还要一步呢!

这样实际我们只要保证每步的收益最大就完成了#define Max(a,b) a>b?a:b
bool canJump(int* nums, int numsSize)
{
int ptr=0;
int move=0;
int pos=0;
while(ptr<numsSize-1)
{
if(ptr+*(nums+ptr)>=numsSize-1)
{
break;
}
for(int i=*(nums+ptr);i>0;i--)
{
int judge=move;
move=Max(move,*(nums+ptr+i)-*(nums+ptr)+i);
if(move!=judge)
{
pos=i;
}
}
if(move==0)
{
return false;
}
else
{
ptr+=pos;
}
pos=0;
move=0;
}
return true;
}同样的思路还可以完成Hard的题目Jump Game II(自己实现下,给自己点信心)
这里也po上II的解法int Max(int a,int b)
{
return a>b?a:b;
}
int jump(int* nums, int numsSize)
{
int ptr=0;
int move=0;
int pos=0;
int count=0;
while(ptr<numsSize-1)
{
if(ptr+*(nums+ptr)>=numsSize-1)
{
count++;
break;
}
for(int i=*(nums+ptr);i>0;i--)
{
int judge=move;
move=Max(move,*(nums+ptr+i)-*(nums+ptr)+i);
if(move!=judge)
{
pos=i;
}
}
ptr+=pos;
count++;
pos=0;
move=0;
}
return count;
}ok这次的题目看上去简单,实际上自己写的话要注意各种边界条件,自己尝试写写吧
最后谢谢大家
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息