4.10 便利蜂笔试
第一题很简单,双循环直接AC
第二题真的太难了,又繁琐又没有思路直接跳过
第三题! 求大佬告知我错哪了, 第三题的思路我是采用贪心,每一部都走允许范围内的最大值,直到走到终点,最后正确率死活只有88%,请问各位大佬是我的代码有问题还是我漏掉了什么EDGE CASE...
代码如下:
package Testing;
import java.util.*;
public class Main
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String[] shop = input.split(",");
int[] distance = new int[shop.length];
for(int i = 0; i < shop.length; i++)
{
distance[i] = Integer.parseInt(shop[i]);
}
int currentPosition = 0;
int totalCar = 0;
boolean ableToReachDes = true;
while(currentPosition < distance.length - 1)
{
boolean ableToReachNext = false;
for(int i = distance[currentPosition]; i > 0; i-- )
{
int targetDes = currentPosition + i;
if(targetDes < distance.length && distance[targetDes] != 0)
{
currentPosition = targetDes;
totalCar++;
ableToReachNext = true;
break;
}
}
if(ableToReachNext != true)
{
ableToReachDes = false;
break;
}
}
if(distance.length <= 1)
System.out.print(0);
else if(!ableToReachDes)
System.out.print(-1);
else
System.out.print(totalCar);
}
}
#便利蜂笔试##Testin云测##笔试题目#import java.util.*;
public class Main
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String[] shop = input.split(",");
int[] distance = new int[shop.length];
for(int i = 0; i < shop.length; i++)
{
distance[i] = Integer.parseInt(shop[i]);
}
int currentPosition = 0;
int totalCar = 0;
boolean ableToReachDes = true;
while(currentPosition < distance.length - 1)
{
boolean ableToReachNext = false;
for(int i = distance[currentPosition]; i > 0; i-- )
{
int targetDes = currentPosition + i;
if(targetDes < distance.length && distance[targetDes] != 0)
{
currentPosition = targetDes;
totalCar++;
ableToReachNext = true;
break;
}
}
if(ableToReachNext != true)
{
ableToReachDes = false;
break;
}
}
if(distance.length <= 1)
System.out.print(0);
else if(!ableToReachDes)
System.out.print(-1);
else
System.out.print(totalCar);
}
}