java - 如何减少以下代码的执行时间?
问题描述
这是为了开发一个游戏。你站在一个名为 game 的 n 元素数组的索引 0 处。从某个索引(其中 0<=i
向后移动:如果单元格 i-1 存在且包含 0 ,您可以返回单元格 i-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();
}
}
解决方案
推荐阅读
- html - 文本对齐如何在 HTML/CSS 中工作
- python - 如果消息有一定数量的反应,则将消息提取到另一个通道 - discord.py 重写
- r - 如何下载小于 3.6 的 R 版本的包“markovchain”
- timestamp - Postman:测试不同时间戳的断言
- powershell - Powershell 使用 System.Windows.Forms.SaveFileDialog 将目录位置选择到变量中
- react-native - 接收react-native应用程序ble发送的数据
- sml - 展平 SML 获取问题的数据类型列表
- javascript - 随机消息回复 Discord.js 2020
- google-bigquery - 如何在 Bigquery 中更改列模式
- python - 使用 numPy 和 matplotlib 绘制函数相对于两个变量的最大值