码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]45 Jump Game II

时间:2015-01-03 13:23:05      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:leetcode

https://oj.leetcode.com/problems/jump-game-ii/

http://blog.csdn.net/linhuanmars/article/details/21356187

public class Solution {
    public int jump(int[] A)
    {
        // [2, 3, 1, 1, 4]
        // [2, 1, 2, 1, 0]
        
        if (A == null || A.length <= 1)
            return 0;
        
        int len = A.length;
        int start = 0;
        int end = 0;
        int jump = 0;
        while (end < len)
        {
            int maxCanGo = 0;
            jump ++;
            for (int i = start ; i <= end ; i ++)
            {
                int curValue = A[i] + i;
                if (curValue >= len - 1)
                {
                    // Reached
                    return jump;
                }
                
                if (curValue > maxCanGo)
                {
                    maxCanGo = curValue;
                }
            }
            
            if (maxCanGo <= end)
            {
                // Can not go further
                return -1;
            }
            
            start = end + 1;
            end = maxCanGo;
        }
        
        return jump;
    }
}


[LeetCode]45 Jump Game II

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1598599

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!