LeetCode——jump-game

Q: given a non-negative integer array, you at the position of a first element of the array
elements in the array represents the maximum length in this position you can jump
determines whether you get to the last element of the array
, for example,
A = [2 , 3,1,1,4], returns to true.
A = [3,2,1,0,4], returns false.

A:

public static boolean canJump(int[] A) {
        if (A.length <= 1)
            return true;
        int index = 0;
        boolean[] flag = new boolean[A.length];
        Arrays.fill(flag, false);
        flag[0] = true;
        int n;
        while (flag[index]) {
            n = index + A[index];
            if (n >= A.length - 1)
                return true;
            for (int i = index; i <= n; i++) {
                flag[i] = true;
            }
            index++;
        }
        return false;
    }

Q: given a non-negative integer array, you at the position of a first element of the array
elements in the array represents the maximum length in this position you can jump
your goal is to use the least number of hops to reach the last element of the array position
, for example,
to give the array a = [2,3,1,1,4]
happened to jump to the last element of the array to a position twice. (From the array subscript 0 1 reaches the position of the length of hop index position 1, and then jump to the position of the last element of length 3 array)

A:

    public int jump(int[] A) {
        if (A.length <= 1)
            return 0;
        int[] num = new int[A.length];
        num[0] = 0;
        for (int i = 1; i < A.length; i++) {
            int min = Integer.MAX_VALUE;
            for (int j = 0; j < i; j++) {
                if (j + A[j] >= i)
                    min = Math.min(min, num[j] + 1);
                num[i] = min;
            }
        }
        return num[A.length - 1];
    }

Guess you like

Origin www.cnblogs.com/xym4869/p/12658384.html