Saturday, April 13, 2013

Jump game I, II (C++ code)

LeetCode Jump Game, Mar 25 '12
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.
 思路:简单递归。偶第二个一次写完bug free的代码,泪~~~

 bool canJump(int A[], int n) {
        if(n <= 1) return true;
        int dist = 0;
        for(int i = n-2; i >= 0; i--){
           dist++;
           if(A[i] >= dist) {dist = 0;}
        }
       if(dist > 0) return false;
      return true;
       
    }

Jump Game II, Mar 17 '12
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.)

思路:每次在可跳的位置中选maximum span,并把对应的结束位置记为下一次跳的newend range.
又一次bug free, 泪~~看来我对int还是很熟的, :P

int jump(int A[], int n) {
    if(n <= 1) return 0;
    int start = 0, end = 0, count = 0;   
    
   while(end < n-1){
      int oldend = end;
      while(start <= oldend) {
        end = max(end, start + A[start]);
        start++;
      }
     count++;
   }

return count;
}

No comments:

Post a Comment