跳转到内容
主菜单
主菜单
移至侧栏
隐藏
规范/协议
协议
算法
JVM
多线程/并发
存储
AI
深度学习
工具箱
最近更改
文章分类
全部文章
WHY42
搜索
搜索
外观
登录
个人工具
登录
欢迎来到Riguz的小站!这是一个私人wiki,用来记录一些我的笔记。
查看“︁55.Jump Game”︁的源代码
页面
讨论
大陆简体
阅读
查看源代码
查看历史
工具
工具
移至侧栏
隐藏
操作
阅读
查看源代码
查看历史
常规
链入页面
相关更改
页面信息
外观
移至侧栏
隐藏
←
55.Jump Game
因为以下原因,您没有权限编辑该页面:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
=Description= {{LeetCode |id=jump-game |no=55 |difficulty=Medium |category=Dynamic Programming |collection=Top 150 |title=Jump Game |summary=You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise.}} Example 1: <syntaxhighlight lang="bash"> Input: nums = [2,3,1,1,4] Output: true </syntaxhighlight> Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. Example 2: <syntaxhighlight lang="bash"> Input: nums = [3,2,1,0,4] Output: false </syntaxhighlight> Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. =Solution= ==1D DP== {{Submission|runtime=418ms|memory=43.4MB|rp=7.2|mp=97.69}} <syntaxhighlight lang="java"> class Solution { public boolean canJump(int[] nums) { /* [2,3,1,1,4] 1 1 2 2 2 */ int []dp = new int[nums.length]; dp[0] = 1; for(int i = 0; i < nums.length; i++) { for(int j = 1; j <= nums[i]; j++){ if(i+j >= dp.length) break; dp[i+j]++; } } for(int i = 0; i < dp.length; i++) { if(dp[i] == 0) return false; } return true; } } </syntaxhighlight> ==1D DP 2== {{Submission|runtime=76ms|memory=43.85MB|rp=17.86|mp=83.06}} <syntaxhighlight lang="java"> class Solution { public boolean canJump(int[] nums) { boolean []dp = new boolean[nums.length]; dp[0] = true; for(int i = 0; i <nums.length; i++) { if(!dp[i]) return false; for(int j = 1; j <= nums[i]; j++) { int next = i + j; if(next >= dp.length) break; if(next == nums.length -1) return true; // reach end already dp[next] = true; } } return dp[nums.length-1]; } } </syntaxhighlight> == Greedy == {{Submission|runtime=2ms|memory=44.02MB|rp=80.65|mp=69.15}} <syntaxhighlight lang="bash"> class Solution { public boolean canJump(int[] nums) { // keep track of the current max reachable position of each step int reachable = 0; for(int i = 0; i < nums.length; i++) { if(i > reachable) return false; reachable = Math.max(reachable, i + nums[i]); } return true; } } </syntaxhighlight> [[Category:Algorithm]] [[Category:Dynamic Programming]] [[Category:Greedy]] [[Category:LeetCode]]
此页面嵌入的页面:
模板:LeetCode
(
查看源代码
)
模板:Submission
(
查看源代码
)
返回
55.Jump Game
。
搜索
搜索
查看“︁55.Jump Game”︁的源代码
添加话题