跳跃游戏

作者: Airycode | 来源:发表于2018-05-10 13:44 被阅读40次

    【链接】https://nanti.jisuanke.com/t/18
    【题目】
    给定一个非负整数数组,假定你的初始位置为数组第一个下标。

    数组中的每个元素代表你在那个位置能够跳跃的最大长度。

    请确认你是否能够跳跃到数组的最后一个下标。

    例如:A = [2,3,1,1,4]A=[2,3,1,1,4] 能够跳跃到最后一个下标,输出true;

    A = [3,2,1,0,4]A=[3,2,1,0,4] 不能跳跃到最后一个下标,输出false。

    输入格式

    第一行输入一个正整数 n(1 \leq n \leq 500)n(1≤n≤500),接下来的一行 nn 个整数,输入数组 A_iA
    i
    ​ 。

    输出格式

    如果能跳到最后一个下标,输出true,否则输出false。

    样例输入
    【代码实现】

    import java.util.Scanner;
    public class Main {
    
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            int n = input.nextInt();
            int max = 1;
            int num[] = new int[n];
            for (int i = 0;i<num.length;i++) {
                num[i] = input.nextInt();   
            }
            
            for (int i = 0;i<num.length;i++) {
                if (i > max) {
                    System.out.println("false");
                    return;
                }
                if (i + num[i] >max) {
                    max = i+num[i];
                }
            }
            
            System.out.println("true");
            return;
            
        }
        
    }
    

    相关文章

      网友评论

        本文标题:跳跃游戏

        本文链接:https://www.haomeiwen.com/subject/admzrftx.html