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

Jan 18 - Jump Game; Array; Greedy;

时间:2016-01-19 14:06:45      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

一开始以为是用DP解决,create a boolean array to store the status which mark whether the person can get to the end from current position.

But, by this methods, we would encounter the worst case, which is there‘re hugh number of index and from which person would finally jump to a trap, i.e., nums[target] = 0. In this case, if we use dp, we need to look through all the previous boolean value and the possibility(the index value larger than the current index value). Thus, the runtime is likely O(n^3).

Greedy, we traverse the array from the len-1 to 0 which is same as DP, the only difference is that when we find a nums[i] = 0 index, the boolean value of the index would be false, we then look through all the pos before this trap pos, use a loop to get all the consecutive positions that would eventually jump to the trap and mark the corresponding status to be false.

 

Code:

public class Solution {
    public boolean canJump(int[] nums) {
        int len = nums.length;
        if(len == 0) return false;
        if(len == 1) return true;
        boolean[] posJump = new boolean[len];
        int i = len-1;
        posJump[i] = true;
        //int target = len-1;
        
        while(i>=1){
            if(i-1+nums[i-1] >= i){
                posJump[i-1] = true;
                i--;
            }
            else{
                posJump[i-1] = false;
                int sink = i-1;
                i = i-1;
                while(i>=1 && (i-1)+nums[i-1] <= sink){
                    posJump[--i] = false;
                }
                if(i >= 1) posJump[i-1] = true;
                i--;
            }
        }
        
        return posJump[0];
    }
    
    /*
    public boolean toPos(int[] nums, int len, int index, boolean[] flag){
        int steps = nums[index];
        if(index + steps >= len-1) {
            flag[index] = true;
            return true;
        }
        if(index < len-1 && steps == 0){
            flag[index] = false;
            return false;
        }
        //int num_step = new int[steps];
        for(int i = 1; i <= steps; i++){
            flag[index] = flag[index] || toPos(nums, len, index+i, flag);
            if(flag[index]) return flag[index];
        }
        return false;
    }
    */
}

  

Jan 18 - Jump Game; Array; Greedy;

标签:

原文地址:http://www.cnblogs.com/5683yue/p/5141802.html

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