Java扫描器在竞争性编码挑战中是一个问题吗?

While I was solving this question with java (https://codingcompetitions.withgoogle.com/kickstart/round/000000000019ffc7/00000000001d3f56)

I first attempted invoking solution() I defined outside main() but it kept giving me a runtime error. I had no clue why it makes an error and suspected it probably doesn't satisfy time limit requirement. So, I removed solution() and integrated into main() then it worked.

这是给出运行时错误的代码。

public class Solution {


    public static void main(String[] args) {
        Scanner scn = new Scanner(System.in);
        int T = scn.nextInt();
        String ans = "";

        for (int i = 0; i < T; i++) {
            ans += "Case #" + (i + 1) + ": " + sol() + "\n";
        }
        System.out.print(ans);

    }

    static int sol() {

        Scanner sc = new Scanner(System.in);

        int N = sc.nextInt();
        int B = sc.nextInt();

        int[] houses = new int[N];

        for (int i = 0; i < N; i++) {
            houses[i] = sc.nextInt();
        }

        Arrays.sort(houses);

        int ans = 0;
        for (int i = 0; i < N; i++) {

            B = B - houses[i];
            if (B < 0)
                break;
            ans++;
        }
        return ans;
    }
}

并且,这是被接受的代码。

public class Solution2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        String ans = "";

        for (int i = 0; i < T; i++){
            int N = sc.nextInt();
            int B = sc.nextInt();

            int[] houses = new int[N];

            for(int j = 0; j<N; j++)
                houses[j]  = sc.nextInt();
            Arrays.sort(houses);
            int cnt = 0;
            for(int j=0; j<N; j++){
                B = B - houses[j];
                if(B<0)
                    break;
                cnt++;
            }

            ans+="\nCase #" + (i+1) + ": " + cnt;

        }

        System.out.println(ans);
    }
}

真的是因为扫描仪花费了太多时间吗?

评论