2016年7月27日星期三

[LeetCode] #55 Jump Game

DP, time complexity: O(n^2) Time Limit Exceeded (这题要用贪心做T_T)

public class Solution {
    // state: f[i] = is ith element reachable
    // function: f[i] = OR(f[j], i - j <= nums[j])
    // initialize: f[0] = true
    // result = f[nums.length]
    public boolean canJump(int[] nums) {
        if (nums == null || nums.length == 0) {
            return false;
        }
        boolean[] f = new boolean[nums.length];
        f[0] = true;
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < i; j++) {
                if (f[j] && j + nums[j] >= i) {
                    f[i] = true;
                    break;
                }
            }
        }
        return f[nums.length - 1];
    }
}

Greedy, time complexity: O(n)
public class Solution {
    public boolean canJump(int[] nums) {
        if (nums == null || nums.length == 0) {
            return false;
        }
        int reachable = nums[0];
        for (int i = 0; i <= reachable && i < nums.length; i++) {
            reachable = Math.max(reachable, i + nums[i]);
        }
        
        return reachable >= nums.length - 1;
    }
}

没有评论:

发表评论