当前位置:网站首页>LeetCode--45. 跳跃游戏Ⅱ(贪心)
LeetCode--45. 跳跃游戏Ⅱ(贪心)
2022-07-28 16:36:00 【爱吃骨头的猫、】
1. 题目描述
难度:困难
2. 题目分析
该题目是LeetCode55.跳跃算法的进阶版,有以下几点需要注意:
- 假设总可以到达数组的最后一个位置
- 要使用最少的跳跃次数
有两种实现方式:
- 最大跨越点算法
找到能够到达最后一个元素的并且下标最小的点,也就是能达到最后一个元素的跨越程度的最大点。然后以此点开始,继续寻找能够到达此点的下标最小的点,知道找到的点的下标为0,也就是数组的首位。时间复杂度最好的情况是O(n),最坏情况是O(n^2) - 贪心算法
从左到右遍历数组,计算每一步所能到达的最大距离,并更新最大距离值。当遍历的下标等于最大距离时,说明这个时候应该跳一步,直到遍历完数组。时间复杂度为O(n)
3. C语言实现
3.1 最大跨越点算法
代码如下:
// 寻找最大跨越点
int findMaxPoint(int* nums, int index){
int i;
for(i = 0; i < index; i++){
if(nums[i]>= index-i)
return i;
}
return i;
}
int jump(int* nums, int numsSize){
int i, index, count;
index = numsSize-1;
count = 0;
if(numsSize == 1) return 0;
while(index != 0){
index = findMaxPoint(nums, index);
count++;
}
return count;
}
运行结果为:
3.2 贪心算法
代码如下:
int jump(int* nums, int numsSize){
// ans为要跳跃的次数
int ans = 0;
// end是目前为止,之前的元素能够到达的最大的点
int end = 0;
// maxPos是不断更新的最大值
int maxPos = 0;
for (int i = 0; i < numsSize - 1; i++)
{
maxPos = nums[i]+i>maxPos?nums[i]+i:maxPos;
// 当遍历的下标遇到end时,说明该跳跃一步了,ans加一
if (i == end)
{
end = maxPos;
ans++;
}
}
return ans;
}
运行结果为:
边栏推荐
- Three ways to dynamically call WebService.Net
- MySQL installation
- [unity] timeline learning notes (VII): Custom clip
- 【p5.js学习笔记】码绘的基础知识
- Public medical database
- Encapsulation, inheritance, polymorphism
- 【Unity】三张图让你看懂ShaderGraph编辑器
- IDEA报错Error running ‘Application‘ Command line is too long解决方案
- Tips--解决No module named matlab.engine的问题
- The solution to the problem that the computer cannot be charged
猜你喜欢
随机推荐
2.2-数据类型
Hgu95av2. Online installation failed
小白如何零基础学习软件测试?
abstract、static、final
MySQL optimization summary
[machine learning notes] regularization: ridge regression
[p5.js] actual copy - chess board
【p5.js】实战练习——无规则对称
[advanced C language] - analyze the storage of micro data in memory [i]
零基础学习软件测试有什么条件?
R language sub() usage
Encapsulation, inheritance, polymorphism
On the non recursive and recursive implementation of finding the nth Fibonacci number respectively
MySQL与IDEA连接
@RequestMapping详解
Map R language
@Detailed explanation of requestmapping
[untitled]
How to bind idea with code cloud
【C语言必看】哟写BUG呢,我敢保证你踩过坑

![[C language note sharing] - dynamic memory management malloc, free, calloc, realloc, flexible array](/img/3f/35c9ff3be5c0ef781ffcb537287a20.png)




![[unity] timeline learning notes (VII): Custom clip](/img/25/0402a28539cb568d5a539a757b2482.png)
![【C语言进阶】——剖析入微数据在内存中的存储[上]](/img/6a/ac723cee2543cd2403a7e58d556c8e.png)
![[untitled]](/img/86/d284eec4eda6a41676d7455b7ea70b.png)
