首页 > 其他 > 详细

[Leetcode]-- Jump Game II

时间:2014-02-07 10:20:19      阅读:372      评论:0      收藏:0      [点我收藏+]

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.)

参考:

水中的鱼: [LeetCode] Jump Game II 解题报告

[解题思路]
二指针问题,最大覆盖区间。
从左往右扫描,维护一个覆盖区间,每扫过一个元素,就重新计算覆盖区间的边界。比如,开始时区间[start, end], 遍历A数组的过程中,不断计算A[i]+i最大值(即从i坐标开始最大的覆盖坐标),并设置这个最大覆盖坐标为新的end边界。而新的start边界则为原end+1。不断循环,直到end> n.

 

bubuko.com,布布扣
public class Solution {
    public int jump(int[] A) {
        int start = 0;
        int end = 0;
        int count = 0;
        int len = A.length;
        if(len == 1) return 0;
        
        while(end < len){
            int max = 0;
            count++;
            for(int i = start; i <=end; i++){
                if(A[i] +i >= len-1){
                    return count;
                }
                
                if(A[i]+i > max){
                    max = A[i]+i;
                }
            }
            
            start = end + 1;
            end = max;
        }
        
        return count;
    }
}
bubuko.com,布布扣

[Leetcode]-- Jump Game II

原文:http://www.cnblogs.com/RazerLu/p/3539134.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!