LeetCode Jump Game II
2015-09-24 03:52
316 查看
原题链接在这里: https://leetcode.com/problems/jump-game-ii/
题目:
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A =
The minimum number of jumps to reach the last index is
题解:
这是的Jump Game进阶版题目。求能跳到最后一个元素的最小步数。
采用了Jump Game中的Method 2. maxJump是维护的当前能跳到的最大位置,maxReach是指从之前的点能reach到得最远位置。
当i 大于之前点能碰到的最大位置时,就需要跳一步,并把maxReach更新为maxJump.
最后返回若是maxJump能到最后一个元素,就返回step, 若是到不了,就说明根本走不到最后一步,返回0.
Time Complexity: O(n). Space: O(1).
AC Java:
题目:
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A =
[2,3,1,1,4]
The minimum number of jumps to reach the last index is
2. (Jump
1step from index 0 to 1, then
3steps to the last index.)
题解:
这是的Jump Game进阶版题目。求能跳到最后一个元素的最小步数。
采用了Jump Game中的Method 2. maxJump是维护的当前能跳到的最大位置,maxReach是指从之前的点能reach到得最远位置。
当i 大于之前点能碰到的最大位置时,就需要跳一步,并把maxReach更新为maxJump.
最后返回若是maxJump能到最后一个元素,就返回step, 若是到不了,就说明根本走不到最后一步,返回0.
Time Complexity: O(n). Space: O(1).
AC Java:
public class Solution { public int jump(int[] nums) { if(nums == null || nums.length == 0){ return 0; } int maxJump = 0; int maxReach = 0; int step = 0; for(int i = 0; i< nums.length && i<=maxJump; i++){ if(i>maxReach){ step++; maxReach = maxJump; } maxJump = Math.max(maxJump, nums[i] + i); } return maxJump<nums.length-1 ? 0:step; } }
相关文章推荐
- LeetCode OJ 03 Longest Substring Without Repeating Characters
- [LeetCode 223] Rectangle Area
- 涵盖各种编程语言的深度学习库整理大全
- HDU 4123 Bob’s Race(树形DP+RMQ)
- java 内存模型
- C++英文单词统计小程序
- POJ - 3468 A Simple Problem with Integers(线段树成段更新,查询区间和)
- POJ - 4047 Garden(线段树成段更新,查询最值)
- [极角排序 扫描法]UVa1606 - Amphiphilic Carbon Molecules
- [等价转换]UVa11054 - Wine trading in Gergovia
- [问题分解]UVa11054 - Wine trading in Gergovia
- iOS实现倒计时功能
- [Hash思想]UVa1152 - 4 Values whose Sum is 0
- IOS开发之实现App消息推送
- LeetCode Jump Game
- vector容器v1、v2之间相互赋值的三种方法及易错点详解
- [LeetCode 205] Isomorphic Strings
- [LeetCode] Palindrome Number & Valid Palindrome - 回文系列问题
- nodejs使用MySQL
- [高效算法 deque运用]UVa120 - Stacks of Flapjacks