首页 > 解决方案 > 如何减少以下代码的执行时间?

问题描述

这是为了开发一个游戏。你站在一个名为 game 的 n 元素数组的索引 0 处。从某个索引(其中 0<=i

  1. 向后移动:如果单元格 i-1 存在且包含 0 ,您可以返回单元格 i-1。

    1. 前进:如果单元格 i+1 包含零,您可以走到单元格 i+1。. 如果单元格 i+leap 包含零,则可以跳转到单元格 i+leap。

如果你站在单元格 n-1 或 i+leap>=n 的值,你可以走或跳出数组的末端并赢得比赛。

换句话说,只要目标索引是包含 0 的单元格,您就可以从索引 i 移动到索引 i-1、i+1 或 i+leap。如果目标索引大于 n-1,您将赢得游戏。

我想到的代码:

import java.util.Scanner;

public class test {
    public static void main(String args[]) {
      Scanner in=new Scanner(System.in);
      int q=in.nextInt();
      int n,leap,move,prevmove,win;
      int game[];

      for(int i=1;i<=q;i++)
      {
          n=in.nextInt();
          leap=in.nextInt();
          move=0;
          prevmove=0;
          win=-1;
        game=new int[n];
      for(int j=0;j<n;j++)
      {
           game[j]=in.nextInt();
      }


     while(win<0) {

            try{
                if(game[move+leap]==0)
                {
                    prevmove=move;
                    move=move+leap;
                    continue;
                }
               }
           catch(Exception e)
           {
               win=1;
               continue;
           }

          try{

                if(game[move+1]==0)
                {
                    prevmove=move;
                    move=move+1;
                    continue;
                }
               }
           catch(Exception e)
           {
               win=1;
               continue;
           }

          try{

                if(game[move-1]==0)
                {
                    if(prevmove!=move-1){
                    prevmove=move;
                    move=move+leap;
                    continue;}
                    else 
                    {
                    win=0;
                    continue;
                    }

                }
               }
           catch(Exception e)
           {
               win=0;
               continue;
           }



          win=0;

          }


       if(win==0)
      System.out.println("NO");
      else
      System.out.println("YES");





      }

in.close();
}
}

标签: javaarrays

解决方案


推荐阅读