Leet Code 45 Jump Game II - 跳跃游戏 - Java
2016-06-22 00:00
489 查看
摘要: Leet Code 45 Jump Game II - 跳跃游戏 - Java
问题原始链接 https://leetcode.com/problems/jump-game-ii
给定一个非负整数数组,你的初始位置为数组的第一个索引。
数组中的每个元素表示你在那个位置的最大跳跃长度。
例如,给定数组 A = [2,3,1,14],到达最后一个索引的跳跃次数为2。(从索引0跳1步到索引1,然后跳3步到最后一个索引。
注意:
你可以假设总是可以到达最后一个索引。
第一种方法,假设数组为a,数组长度为n,申请一个数组step
,step[i]表示跳到i位置需要的最少步数,step[0]=1。从左往右扫描数组,在位置i时更新step[i+1..i+a[i]],step[j]=min(step[j], step[i]+1)。
这种方法性能太差。LeetCode超时。
第二种方法
整型变量jump,表示目前跳了多少次。整型变量cur,表示如果只能跳jump次,能达到的最远的位置。整型变量next,表示如果再多跳一次,能达到的最远的位置。
问题原始链接 https://leetcode.com/problems/jump-game-ii
给定一个非负整数数组,你的初始位置为数组的第一个索引。
数组中的每个元素表示你在那个位置的最大跳跃长度。
例如,给定数组 A = [2,3,1,14],到达最后一个索引的跳跃次数为2。(从索引0跳1步到索引1,然后跳3步到最后一个索引。
注意:
你可以假设总是可以到达最后一个索引。
第一种方法,假设数组为a,数组长度为n,申请一个数组step
,step[i]表示跳到i位置需要的最少步数,step[0]=1。从左往右扫描数组,在位置i时更新step[i+1..i+a[i]],step[j]=min(step[j], step[i]+1)。
这种方法性能太差。LeetCode超时。
public class Solution { public static int jump(int[] nums) { if (nums == null || nums.length <= 1) { return 0; } int[] step = new int[nums.length]; for (int i = 0; i < nums.length - 1; i++) { int end = i + nums[i]; if (end >= nums.length - 1) { return step[i] + 1; } for (int j = i + 1; j <= i + nums[i] && j < nums.length; j++) { step[j] = step[j] == 0 ? step[i] + 1 : Math.min(step[j], step[i] + 1); } } return step[nums.length - 1]; } }
第二种方法
整型变量jump,表示目前跳了多少次。整型变量cur,表示如果只能跳jump次,能达到的最远的位置。整型变量next,表示如果再多跳一次,能达到的最远的位置。
public class Solution { public static int jump(int[] nums) { if (nums == null || nums.length <= 1) { return 0; } int jump = 0; int cur = 0; int next = 0; for (int i = 0; i < nums.length; i++) { if (cur < i) { jump++; cur = next; } next = Math.max(next, i + nums[i]); } return jump; } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解