您的位置:首页 > 其它

【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:

//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