【LeetCode】45.Jump Game II(Hard)解题报告
2018-01-31 11:18
513 查看
【LeetCode】45.Jump Game II(Hard)解题报告
题目地址:https://leetcode.com/problems/jump-game/description/
题目描述:
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 1 step from index 0 to 1, then 3 steps to the last index.)
Note: You can assume that you can always reach the last index.
Solution1:
Solution2:
Date:2018年1月31日
题目地址:https://leetcode.com/problems/jump-game/description/
题目描述:
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 1 step from index 0 to 1, then 3 steps to the last index.)
Note: You can assume that you can always reach the last index.
Solution1:
//Edward shi //贪心 //time:O(n) //space:O(1) class Solution { public int jump(int[] nums) { if(nums.length < 2 || nums == null) return 0; int maxNext = 0; //能走的最远距离 int curMaxArea = 0; //当前能走到的最大距离 int res = 0; for(int i=0 ;i<nums.length-1 ; i++){ maxNext = Math.max(maxNext , nums[i]+i); if(i == curMaxArea){ res++; curMaxArea = maxNext; } } return res; } }
Solution2:
//Edward shi //BFS,暂时不理解,以后再看 //time:O(n) //space:O(1) class Solution { public int jump(int[] nums) { if(nums.length < 2 || nums == null) return 0; int maxNext = 0; //能走的最远距离 int curMaxArea = 0; //当前能走到的最大距离 int level = 0; int i=0; while(curMaxArea-i+1>0){ level++; for(; i<=curMaxArea ; i++){ //i=0就出错了 maxNext = Math.max(maxNext,nums[i]+i); if(maxNext >= nums.length - 1){ return level; } } curMaxArea = maxNext; } return 0; } }
Date:2018年1月31日
相关文章推荐
- 【LeetCode】664.Strange Printer(hard)解题报告
- 【LeetCode】297.Serialize and Deserialize Binary Tree(Hard)解题报告
- 【LeetCode】10.Regular Expression Matching(hard)解题报告
- 【LeetCode】42.Trapping Rain Water(Hard)解题报告
- 【LeetCode】291.Word Pattern II(Hard)解题报告
- 【LeetCode】4.Median of Two Sorted Arrays(Hard)解题报告
- 【LeetCode】282.Expression Add Operators(Hard)解题报告
- 【LeetCode】52.N-Queens II(hard)解题报告
- 【LeetCode】726.Number of Atoms(Hard)解题报告
- 【LeetCode】403. Frog Jump(Hard)解题报告
- 【LeetCode】164.Maximum Gap(Hard)解题报告
- 【LeetCode】41. First Missing Positive(Hard)解题报告
- 【LeetCode】135.Candy(hard)解题报告
- 【LeetCode】99.Recover Binary Search Tree(Hard)解题报告
- 【LeetCode】145.Binary Tree Postorder Traversal(Hard)解题报告
- 【LeetCode】123.Best Time to Buy and Sell Stock III(Hard)解题报告
- 【LeetCode】51.N-Queens(hard)解题报告
- 【LeetCode】330.Patching Array(Hard)解题报告
- 【LeetCode】321.Create Maximum Number(Hard)解题报告
- 【LeetCode】301.Remove Invalid Parentheses(hard)解题报告