当前位置:网站首页>算法---跳跃游戏(Kotlin)
算法---跳跃游戏(Kotlin)
2022-08-11 09:58:00 【小米科技Android 研发曹新雨】
题目
给定一个非负整数数组 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]表示是否可以跳到i的位置,我们只需要从数组开始,如果当前位置可以跳到,那就把从当前的每一位到可以跳到的区间置为true,如果数组的最后一位是true,那就表示可以达到
方法二:第一个方法的数组可以去掉 从第一个位置开始,直接记录一个最远的位置,在这个最远的位置之内,所有的都可以位置都可以调到。我们在这个基础上进行最远距离的更新
解决方法
方法一:
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.属于贪心算法,每一步都尽量获取到最大值,使用暴力解决的方法,也挺好写,就是当数组太大的时候,效率太低,过不了。
2.算法就是时间和空间的利用啊,第一个方法可能不错,但是浪费了没有必要的空间。
边栏推荐
- Primavera Unifier advanced formula usage sharing
- A few days ago, Xiaohui went to Guizhou
- 收集awr
- HDRP shader 获取阴影(Custom Pass)
- MySQL约束
- How to determine the neural network parameters, the number of neural network parameters calculation
- Network model (U - net, U - net++, U - net++ +)
- 前几天,小灰去贵州了
- 二维数组名的用途
- HStreamDB v0.9 released: Partition model extension, support for integration with external systems
猜你喜欢
随机推荐
WooCommerce Ecommerce WordPress Plugin - Make American Money
关于ts的一些泛型关键字用法
VC6.0 +WDK 开发驱动的环境配置
卷积神经网络梯度消失,神经网络中梯度的概念
清除微信小程序button的默认样式
How to determine the neural network parameters, the number of neural network parameters calculation
1002 A+B for Polynomials
Quickly submit a PR (Web) for OpenHarmony in 5 minutes
QTableWidget 使用方法
What is the difference between the qspi interface and the ordinary four-wire SPI interface?
数据库基础
自定义卷积核的分组转置卷积如何实现?
HDRP Custom Pass Shader Get world coordinates and near clipping plane coordinates
VideoScribe卡死解决方案
零基础创作专业wordpress网站12-设置标签栏图标(favicon)
WordpressCMS主题开发01-首页制作
OAK-FFC系列产品上手指南
HStreamDB v0.9 released: Partition model extension, support for integration with external systems
Adobe LiveCycle Designer 报表设计器
困扰所有SAP顾问多年的问题终于解决了









