Java中的汽车加油问题任何人都可以找出while循环条件中的任何错误吗?

问题描述

import java.util.*;
import java.io.*;

public class CarFueling {
 static int compute_refills(int dist,int tank,int stops[],int n){
    
        int current_refills=0;
        int num_refills=0;
        int last_refill=0;
        while(current_refills<=n) {
             last_refill = current_refills;
            while ((current_refills <= n) && (stops[current_refills + 1] - stops[last_refill]) <= tank) {
                current_refills = current_refills + 1;
            }

            if (current_refills == last_refill)
                return -1;
            if (current_refills <= n)
                num_refills = num_refills + 1;


        }
        return num_refills;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int dist = scanner.nextInt();
        int tank = scanner.nextInt();
       int n = scanner.nextInt();
        int stops[] = new int[n*n*n];// to solve array index out of bound exception increase the size of the array
        for (int i = 0; i < n; i++) {
            stops[i] = scanner.nextInt();
        }

       System.out.println(compute_refills(dist,tank,stops,n));

    }
}

我认为while循环条件有些问题。
输入:
950 400
4
200375550750
我的输出:
1
正确的输出:
2

解决方法

如果你看

(current_refills <= n) && (stops[current_refills + 1] ... )

部分,两件事:

  • current_refills <= nn-1(n元素数组的最后一个元素,因为第一个元素的索引为0)和n(已在数组外部)都成立)
  • 然后stops[current_refills + 1]访问元素“后”,在这两种情况下,元素的数量比最大值高1或2个元素。

但是实际上这是可行的,只是您可以在旅程开始时添加0,在旅程结束时添加dist

int n = scanner.nextInt();
int stops[] = new int[n+2];
stops[0] = 0; // well,it is 0 already
stops[n+1] = dist;
for (int i = 1; i <= n; i++) {
    stops[i] = scanner.nextInt();
}

然后compute_refills()可能会正常工作(尽管我尚未检查)。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...