Monday, November 23, 2015

[leetcode] Jump Game II

Be careful with the thinking (off by 1?)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution {
    public int jump(int[] nums) {
        if (nums == null || nums.length <= 1) return 0;
        int curOvered = 0;
        int nextOvered = 0;
        int jump = 0;
        for (int i = 0; i < nums.length; i++){
            nextOvered = Math.max(nextOvered, nums[i]+i);
            if (nextOvered >= nums.length-1){
                jump++;
                break;
            }
            if (curOvered == i){
                curOvered = nextOvered;
                nextOvered = 0;
                jump++;
            }
        }
        return jump;
    }
}

No comments:

Post a Comment