Leetcode 贪心算法 jump-game

给定一个非负整数数组,你最初位于数组的第一个位置。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

判断你是否能够到达最后一个位置。

示例 1:

输入: [2,3,1,1,4]
输出: true
解释: 从位置 0 到 1 跳 1 步, 然后跳 3 步到达最后一个位置。
示例 2:

输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。

这道题我开始的思路是给定的数字是非负,那么如果存在0,就不可能到达终点了。这个不一定的,如果0后面的值也能到达,后面的值还可以往后跳。并且如果从最后一位开始连续多个都是0的话,也是有可能跳到终点的。
这个是不正确思路的代码。

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

运用广度优先搜索算法去做
这道题类似于坐标轴上某个点 有+1, -1, *2几种走法,求走到某个点最少的步骤。

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by Administrator on 2018/5/7 0007.
 */
public class Solution {
    public static void main(String[] args) {
        int[] a = { 2,3,1,1,4};
        int[] b = {3,2,1,0,4};
        System.out.println(canJump(a));
        System.out.println(canJump(b));
    }

    public static boolean canJump(int[] A) {
        if (A == null || A.length == 0) {
            return false;
        }
        Queue<Node> queue = new LinkedList<>();
        int far = 0, nextFar = 0;
        queue.add(new Node(0, A[0]));
        HashSet<Integer> set = new HashSet<>();
        set.add(0);
        while (queue.size() > 0) {
            Node node = queue.poll();
            if (node.index + node.value >= A.length -1) {
                return true;
            } else {
                nextFar = nextFar < node.index + node.value? node.index + node.value : nextFar;
            }
            for (int i = far; i <= nextFar; i++) {
                if (!set.contains(i)) {
                    queue.add(new Node(i, A[i]));
                    set.add(i);
                }
            }
            far = nextFar;
        }
        return false;
    }

    public static class Node {
        int index;
        int value;
        public Node(int index, int value) {
            this.index = index;
            this.value = value;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_31617121/article/details/80230585