Saturday, April 16, 2016

Jump Game I + II -- Leetcode

1.Jump Game I:
Question:
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.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
Answer:
Greedy method:

 public boolean canJump(int[] nums) {
        int max=nums[0];
        for(int i=0;i<=max;++i){
           if(max>=nums.length-1){
               return true;
           }
           if(i+nums[i]>max){
               max=i+nums[i];
           }
        }
        return false;
    }


2.Jump Game II:
Question:
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.)
Note:
You can assume that you can always reach the last index.
Answer:
Greedy method:

 public int jump(int[] nums) {
        int len=nums.length;
        int max=0;
        int[] count=new int[len];
        
        for(int i=0;i<=max;++i){
            if(max>=len-1){
                return count[len-1];
            }
            int curMax=i+nums[i];
            if(curMax > max){
                for(int k=max+1;k<=curMax&&k<=len-1;++k){
                    count[k] = count[i] + 1;
                }
                max = curMax;
            }
        }
        return -1;
    }

No comments:

Post a Comment