jump game ii

原创 2015年07月08日 12:16:20

中等 跳跃游戏 II

33%
通过

给出一个非负整数数组,你最初定位在数组的第一个位置。

数组中的每个元素代表你在那个位置可以跳跃的最大长度。   

你的目标是使用最少的跳跃次数到达数组的最后一个位置。

您在真实的面试中是否遇到过这个题? 
Yes
样例

给出数组A = [2,3,1,1,4],最少到达数组最后一个位置的跳跃次数是2(从数组下标0跳一步到数组下标1,然后跳3步到数组的最后一个位置,一共跳跃2次)

public class Solution {
    public int jump(int[] nums) {
        if(nums == null || nums.length == 0){
            return -1;
        }
        int start = 0, end = 0, jump = 0;
        while(end < nums.length -1){
            jump++;
            int farthest = end;
            for(int i = start; i <= end; i++){
                farthest = Math.max(farthest,nums[i]+i);
                if(farthest >= nums.length -1){
                    return jump;
                }
            }
            //跳完这一步,下次开始的地方,保证所有的都被遍历到
            start = end + 1;
            end = farthest;
        }
        return 0;
    }
}
/**
 * nums: [2,3,1,1,4] nums.length = 5;
 * start = 0, end = 0, jump = 0;
 * while(end < nums.length -1){
 * 
 *  jump = 1;
 *  farthest = end = 0;
 *  i = 0
 *      farthest = max(0,2) = 2;
 *  start = end + 1 = 1;
 *  end = farthest = 2;
 * 
 *  jump = 2;
 *  farthest = end = 2;
 *  i = 1
 *      farthest = max(2,4) = 4;
 *  return jump;
 */
 
 


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode第45之 Jump Game II

看了好几种算法实现,感觉这里说的最清楚,也比较简单,本算法思想也是来源于此。 解法看完这道题目,可能大部分的读者都能够想出这样一个相对简单的解法:将每个位置都看作一个点,并从第i个点向它之后的num...

LeetCode Jump Game II

Description: Given an array of non-negative integers, you are initially positioned at the first...

Jump Game II

Given an array of non-negative integers, you are initially positioned at the first index of the arra...

LeetCode:Jump Game I && II

Jump Game   Given an array of non-negative integers, you are initially positioned at the first...

LeetCode No.45 Jump Game II

LeetCode No.45 Jump Game II

[C++]LeetCode: 104 Jump Game II (局部最优和全局最优法)

题目: Given an array of non-negative integers, you are initially positioned at the first index of t...

LeetCode 45. Jump Game II

45. Jump Game II Given an array of non-negative integers, you are initiallypositioned at the first i...

42. Trapping Rain Water\54. Spiral Matrix\45. Jump Game II

Trapping Rain Water 题目描述 代码实现 Spiral Matrix 题目描述 代码实现 Jump Game II 题目描述 代码实现42. Trapping Rain Water题...

Leetcode45. Jump Game II

Leetcode45. Jump Game II

[leetcode] 45.Jump Game II

问题描述: Given an array of non-negative integers, you are initially positioned at the first index of t...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)