当前位置:网站首页>Algorithm---Jumping Game (Kotlin)
Algorithm---Jumping Game (Kotlin)
2022-08-11 10:03:00 【Xiaomi Technology Android R&D Cao Xinyu】
题目
给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 .
数组中的每个元素代表你在该位置可以跳跃的最大长度.
判断你是否能够到达最后一个下标.
示例 1:
输入:nums = [2,3,1,1,4]
输出:true
解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标.
示例 2:
输入:nums = [3,2,1,0,4]
输出:false
解释:无论怎样,总会到达下标为 3 的位置.但该下标的最大跳跃长度是 0 , 所以永远不可能到达最后一个下标.
提示:
1 <= nums.length <= 3 * 104
0 <= nums[i] <= 105
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/jump-game
著作权归领扣网络所有.商业转载请联系官方授权,非商业转载请注明出处.
解决思路
方法一:定义一个数组,dp[i]Indicates whether it is possible to jump toi的位置,We just need to start with the array,If the current location can jump to,Then set the interval from the current bit to the jump totrue,If the last bit of the array is true,That means it can be achieved
方法二:The array of the first method can be removed 从第一个位置开始,Directly record a farthest position,within this furthest location,All positions can be adjusted.We make the furthest update on this basis
解决方法
方法一:
fun canJump(nums: IntArray): Boolean {
val dp = Array(nums.size) {
false }
dp[0] = true
nums.forEachIndexed {
index, i ->
if (dp[index]) {
Arrays.fill(dp,index,(index + i + 1).coerceAtMost(nums.size),true)
}
}
return dp[nums.size - 1]
}
方法二
优化版本:
fun canJump3(nums: IntArray): Boolean {
var maxRight = nums[0]
nums.forEachIndexed {
index, i ->
if (index <= maxRight){
maxRight = maxRight.coerceAtLeast(index + i)
}
}
return maxRight >= nums.size - 1
}
总结
1.属于贪心算法,Try to get the maximum value at each step,Use brute force solutions,well written too,That is when the array is too large,效率太低,过不了.
2.Algorithms are the use of time and space,The first method might be fine,But unnecessary space is wasted.
边栏推荐
- 27岁了,目前从事软件测试,听些老一辈的人说测试前途是IT里最差的,是这样吗?
- 【luogu CF1427F】Boring Card Game(贪心)(性质)
- 基于卷积的神经网络系统,卷积神经网络毕业论文
- HStreamDB v0.9 released: Partition model extension, support for integration with external systems
- snapshot standby switch
- HDRP Custom Pass Shader 获取世界坐标和近裁剪平面坐标
- WooCommerce Ecommerce WordPress Plugin - Make American Money
- mindspore 执行模型转换为310的mindir文件显示无LRN算子
- Adobe LiveCycle Designer 报表设计器
- 阿里二面:JVM调优你会吗?
猜你喜欢
随机推荐
如何开手续费低靠谱正规的期货账户呢?
MySQL数据库基础_常用数据类型_表设计
pycharm 取消msyql表达式高亮
Software custom development - the advantages of enterprise custom development of app software
淘宝/天猫获得淘宝app商品详情原数据 API
【Prometheus】Alertmanager告警全方位讲解
SQL语句
网络模型(U-net,U-net++, U-net+++)
Deploying Robot Vision Models Using Raspberry Pi and OAK Camera
基于PSO在满足可靠性的基础上实现费用最优MATLAB仿真(含完整matlab代码)
假设检验:正态性检验的那些bug——为什么对同一数据,normaltest和ktest会得到完全相反的结果?
PowerMock for Systematic Explanation of Unit Testing
保证金监控中心保证期货开户和交易记录
基于卷积的神经网络系统,卷积神经网络毕业论文
海信自助机-HV530刷机教程
Segmentation Learning (loss and Evaluation)
VC6.0 +WDK 开发驱动的环境配置
服务器和客户端的简单交互
pycharm cancel msyql expression highlighting
【luogu CF1427F】Boring Card Game(贪心)(性质)









