为什么8个案例中有2个出现运行时错误?

时间:2017-02-09 19:31:54

标签: java arrays sorting runtime-error

我已经完成了How can I make a multipart/form-data POST request using Java?并使用下面对数组进行排序的代码通过了8个测试用例中的6个,然后增加max int出现的频率并打印该值:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int numCandles = in.nextInt();
        int height[] = new int[numCandles];
        for(int height_i=0; height_i < numCandles; height_i++){
            height[height_i] = in.nextInt();
        }

        //Option 2: Sort the array, then count the number that are highest.
        Arrays.sort(height);
        int max = height[height.length - 1];
        int index = height.length - 1;
        int freq = 0;
        while(height[index] == max) {
            freq++;
            index--;
        }
        System.out.println(freq);
    }
}

它没有通过测试用例#6(Hackerrank's "Birthday Cake Candles" challenge)或测试用例#7。简而言之,测试用例#6是100,000次出现的int 999999,测试用例#7是100,000次出现的int 1.两者的预期输出应该是100000。

我认为它可能遇到运行时错误,因为我在数组上调用的排序方法和数组试图一遍又一遍地对这些值进行排序?谁能解释为什么我的代码不适用于这两个测试用例?

3 个答案:

答案 0 :(得分:1)

当输入中的所有值都相同时(如您包含的样本输入中),此循环中的条件将为true,直到index减少为-1,此时您&# 39;得到ArrayIndexOutOfBoundsException

while(height[index] == max) {
    freq++;
    index--;
}

为循环条件添加范围检查,例如:

while (index >= 0 && height[index] == max) {

通过此更改,解决方案将通过所有测试。但这是一个效率低下的解决方案。您对输入进行了排序以减少while循环中的迭代次数。但排序是O(n log(n))操作,比使用O(n)的简单过滤慢。例如:

int numCandles = in.nextInt();
int heights[] = new int[numCandles];
int m = Integer.MIN_VALUE;
for (int i = 0; i < numCandles; i++) {
    heights[i] = in.nextInt();
    m = Math.max(m, heights[i]);
}

final int max = m;
long freq = IntStream.of(heights).filter(x -> x == max).count();
System.out.println(freq);

答案 1 :(得分:0)

您正在获得异常的出站,因为当您的数量小于0时,您将到达某个部分

while(height[index] == max) {

    freq++;
                if(index == 0)
        break;
    index--;
}   

这是我解决此问题的方法

Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int height[] = new int[n];
        for(int height_i=0; height_i < n; height_i++){
            height[height_i] = in.nextInt();
        }
        Arrays.sort(height);
        int counter = 0;
        int different = height[n-1];
       for(int height_i=n-1; height_i >=0 ; height_i--){

           if(different ==height[height_i] )
            {
            counter = counter  + 1;   


           }
           else 
               {
               break;
           }

        }
        System.out.println(counter);
    }

这是我的解决方案。我认为最好使用一段时间。

答案 2 :(得分:-1)

简单解决方案

static int birthdayCakeCandles(int[] arr) {
          int max = arr[0];
    int count = 0;
    for(int i =0; i<arr.length;i++) {

        if(max < arr[i]) {

            max = arr[i];
        }

    }
    for(int i =0; i<arr.length;i++) {

        if(max == arr[i]) {

            count++;
        }

    }
 return count;
}