微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

跳转游戏leetcode问题中预期输出不正确

如何解决跳转游戏leetcode问题中预期输出不正确

我正在用leetcode进行数据结构练习。

问题:https://leetcode.com/problems/jump-game/

对于这个问题,当我提交我的解决方案时,输入失败

[2,5,0]

Leetcode期望输出为true,但我无法理解为什么它应该为true。有人可以向我解释这个问题吗?

enter image description here

解决方法

我认为您在这里感到困惑,“代表您在该位置的最大跳跃长度”。

Input: nums = [2,5,0] 

输出:true

说明:从索引0到1跳1步,然后再跳2步到最后一个索引。

每个索引处的跳转长度最多为索引的值。

,

以下是根据您的输入[2,0]进行的说明。此处,第i个索引/位置的值表示您可以从第i个索引/位置获取的最大跳跃。因此,输入将通过以下方式进行解释,

Index/position       value                      What this means?
    0                  2       You can take maximum 2 jumps from index 0 i.e. you can reach index 1 and 2 from index 0 [0 --(1st jump)--> 1 --(2nd jump)--> 2]
    1                  5       You can take maximum 5 jumps from index 1 i.e. you can reach index 2 and 3 (array ends at index 3) from index 1 [1 --(1st jump)--> 2 --(2nd jump)--> 3]
    2                  0       You cannot jump to any other index from index 2.
    3                  0       You cannot jump to any other index from index 3 (the array ends here anyway).

关注最大跳跃部分是因为您可以选择较少的跳跃次数来达到最后一个索引。现在,我希望这个问题对您很清楚,让查看解决方案,即为什么期望的答案是true

[2,0]-这里的目标是从索引0到达索引3。 您必须确保您不会从索引2结束,因为您不能从索引2进行任何跳转,即无法从索引2到达最后一个索引3。因此,您必须首先从索引0进行1跳转(您可以从索引0开始最多跳2次,到达索引1,然后从索引1开始最多跳2次(从索引0开始最多跳5次),直到最后一个索引3。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。