LeetCode 45. Jump Game II|贪心算法
来源:互联网 发布:怎么开通淘宝直播间 编辑:程序博客网 时间:2024/06/05 16:47
题目描述
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.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
Note:
You can assume that you can always reach the last index.
算法分析
这道题是困难的难度,但实际上也不太难,这道题有很多种解法,我的解法效率虽然不算很高,但是使用了单纯的贪心算法,容易理解,而且还可以把路径保存起来。
我这个算法在于,每一次选择下一个点时,会判断选择该点之后,是不是能够跳的更加远,这就需要有一个内部的循环进行判断。判断在目前位置到可到达的位置之间,选择一个能够让我下一步跳的更远的点。思想十分简单,但因为有内部循环,所以效率会比起加入动态规划算法慢了许多,不过也可以通过。时间复杂度最好的是O(N),最差的不会超过O(N^2)。
int jump(vector<int>& nums) { if(nums.size()<2) return 0; int i = 0; int count = 0; while(i<nums.size()-1){ count++; if(i+nums[i]>=nums.size()-1) return count; int j = 1; int best = 0; int max_jump= 0; for( ; j <= nums[i] ; j++){ if(nums[i+j]+j>max_jump){ max_jump = nums[i+j]+j; best = j; } } i+=best; } return count;}
- LeetCode 45. Jump Game II|贪心算法
- [LeetCode]45. Jump Game II &&贪心算法
- Leetcode 贪心 Jump Game II
- [leetcode][贪心] Jump Game II
- LeetCode Jump Game II(贪心)
- Jump Game II-贪心算法
- LeetCode Jump Game(贪心算法)
- 45. Jump Game II(贪心)
- leetcode 45. Jump Game II 贪心算法&&DFS深度优先搜索
- [LeetCode]Jump Game II(贪心&&DP!!!!!)
- leetCode #45 Jump Game II 贪心
- leetcode -- Jump Game II -- 贪心,要看
- Jump Game II leetcode 45 贪心
- LeetCode --- 45. Jump Game II
- LeetCode 45.Jump Game II
- [Leetcode] 45. Jump Game II
- [leetcode] 45.Jump Game II
- [leetcode] 45.Jump Game II
- epoll模型的理解封装与应用
- 【11月13日】排序算法的效率问题+彩蛋
- 从傅里叶级数到傅里叶变换
- 深入理解观察者模式(二)
- 程序日志
- LeetCode 45. Jump Game II|贪心算法
- Android四大组件之一:Activity总结(下)
- PHP的继承方法如何获取子类名?
- String Fundamentals
- 【水水水】【洛谷 U4566】赛车比赛
- 视频App市场总结
- Spring笔记一 SpringInAction第二章(一):装配Bean(一)
- 【C语言】用递归实现字符串逆序的曲折之路
- 圆周卷积(circular convolution)