Leetcode 贪心 Jump Game

来源:互联网 发布:什么软件外卖货到付款 编辑:程序博客网 时间:2024/05/26 02:55

Jump Game

 Total Accepted: 18745 Total Submissions: 68916My 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.





题意:给一个包含非负整数的数组,每个数表示最大能跳跃的距离,最初的位置在
下标 0处,问能否跳到数组的最后一个位置
思路0:贪心
问能否跳最后一个位置,可以将问题转换为跳到最后一个位置后剩余的最大步数(如果不能跳到,提早结束程序)。
通过求到每个位置剩余的最大步数可求到最后一个位置的剩余的最大步数。
设 step = A[0],到下一个位置时,step--,并且step = max(step, A[1]);
复杂度:时间O(n),空间O(1)


bool canJump(int A[], int n){if(n == 0) return false;int step = A[0];for(int i = 1; i < n; ++i){if(step <= 0) return false;--step;step = max(step, A[i]);}return true;}


0 0
原创粉丝点击