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

LeetCode "Jump Game II"

时间:2014-08-01 13:32:21      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   art   ar   div   new   

Greedy, Greedy, Greedy.. It is all about maximum interval update.

One trick is, we start looping over each element from the one nearest to end to farthest one - because the nearer the index is, more hopeful it could finish earlier. With this optimization, I got it passed with only 24ms.

class Solution {
public:
    
    int jump(int A[], int n) {
        if (n <= 1) return 0;
        int last = 0, inx = 0;
        int cnt = 0;
        while (inx < n)
        {
            int newMaxInx = 0;
            int tmp_i = inx + 1;
            while (tmp_i--)
            {
                if (tmp_i < last) break;
                newMaxInx = std::max(newMaxInx, A[tmp_i] + tmp_i);
                if (newMaxInx >= n - 1) return cnt + 1;
            }
            last = inx;
            inx = newMaxInx;
            cnt++;
        }
        return cnt;
    }
};

 

LeetCode "Jump Game II",布布扣,bubuko.com

LeetCode "Jump Game II"

标签:style   blog   color   io   art   ar   div   new   

原文地址:http://www.cnblogs.com/tonix/p/3884666.html

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