算法分析与设计week04--55.Jump Game
来源:互联网 发布:好用的洗面奶知乎 编辑:程序博客网 时间:2024/06/07 01:06
55.Jump Game
Description
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.
Example
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
Analyse
题意:
给出一个非负数组,初始位置为数组的第一个位置,数组中的元素表示你能跳的最远距离。问是否可以到达最后一个索引位置。
贪心算法:
第一步:从第一个位置开始,计算从该位置出发所能到达的最远距离,然后和sums.length - 1作比较:
“局部最优和全局最优解法”:维护一个到目前为止能跳到的最远距离,以及从当前一步出发能跳到的最远距离。局部最优local = sums[i] + i,而全局最优则是global = max(global, local)。
class Solution {public: bool canJump(vector<int>& nums) { int local = 0; int global = 0; for (int i = 0; i < nums.size(); i++) { if (global < i) break; // 任意 i 位置出现maxstep为0的情况,则说明无法继续向前移动 local = i + nums[i]; global = max(global, local); } return nums.size() - 1 <= global; }};
复杂度分析
时间复杂度:O(n)
空间复杂度:O(1)
另一种贪心解法:逆向考虑
(官网参考答案:https://leetcode.com/problems/jump-game/solution/)
From a given position, when we try to see if we can jump to a GOOD position, we only ever use one - the first one (see the break statement). In other words, the left-most one. If we keep track of this left-most GOOD position as a separate variable, we can avoid searching for it in the array.
class Solution {public: bool canJump(vector<int>& nums) { int lastPos = nums.size() - 1; for (int i = lastPos; i >= 0; i--) { if (i + nums[i] >= lastPos) { lastPos = i; } } return lastPos == 0; }};
- 算法分析与设计week04--55.Jump Game
- 算法分析与设计week04--45.Jump Game II
- 算法分析与设计第九周:45. Jump Game II
- 算法分析与设计课程(9):【leetcode】Jump Game
- 【数据结构与算法】Jump Game
- leetcode 55. Jump Game-贪心算法
- LeetCode 55. Jump Game|贪心算法
- leetcode.55.Jump Game(medium)[贪心算法]
- leetcode 55. Jump Game 贪心算法
- 55. Jump Game 【Medium】 贪心算法
- jump game 贪心算法
- 算法设计周记(二)--Jump Game
- 55. Jump Game && 45. Jump Game II
- 55. Jump Game. 45. Jump Game II
- 数据结构与算法[LeetCode]——Jump Game I II
- 【算法分析与设计】【第三周】679. 24 Game
- Jump Game II-贪心算法
- LeetCode Jump Game(贪心算法)
- LintCode 最接近零的子数组和
- 习题1.6程序开发的基本步骤
- webdriver.chrome()禁止加载图片
- 计算圆,正方形和长方形的面积
- C开发笔试题三道
- 算法分析与设计week04--55.Jump Game
- XML
- 高并发服务器
- MFC框架界面开发(五):基于文档模板架构的软件
- Servlet知识
- Codeforce 101581 problem C 【gcd+预处理】
- java小程序——八皇后
- 集合之间的操作util-在全集allSet中标识出在子集sonSet 出现过的元素
- libmaxminddb