整数慢于int吗?

huangapple go评论69阅读模式
英文:

Is Integer slower than int?

问题

import java.util.Scanner;
import java.util.Arrays;

class Main {
    public static void main(String[] args) throws java.lang.Exception {
        Scanner sc = new Scanner(System.in);
        int scene = sc.nextInt();
        int j = 1;
        while (j <= scene) {
            int need = sc.nextInt();
            int frnds = sc.nextInt();
            int arr[] = new int[frnds];
            for (int i = 0; i < frnds; i++)
                arr[i] = sc.nextInt();
            Arrays.sort(arr);
            int count = 0;
            System.out.println("Scenario #" + j + ":");
            for (int i = frnds - 1; i >= 0; i--) {
                count++;
                need -= arr[i];
                if (need <= 0) {
                    System.out.println(count);
                    break;
                }
            }
            if (need > 0)
                System.out.println("impossible");
            System.out.println();
            j++;
        }
    }
}
英文:

In competitive programming I used Integer instead of int but it got me TLE error Can you tell me why? Basically i have to just sort the array and traverse it.
my code is here

    class Main
    {
    public static void main (String[] args) throws java.lang.Exception
    {
	  Scanner sc = new Scanner(System.in);
      int scene = sc.nextInt();
      int j=1;
      while(j&lt;=scene)
      {
        int need = sc.nextInt();
        int frnds = sc.nextInt();
        int arr[] = new int[frnds];
        for(int i=0;i&lt;frnds;i++)
            arr[i] = sc.nextInt();
        Arrays.sort(arr);
        int count =0;
        System.out.println(&quot;Scenario #&quot;+j+&quot;:&quot;);
        for(int i=frnds-1;i&gt;=0;i--)
        {
            count++;
            need -= arr[i];
            if(need&lt;=0) {
                System.out.println(count);
                break;
            }
        }
        if(need&gt;0)
            System.out.println(&quot;impossible&quot;);
        System.out.println();
        j++;
    }
   }
  }

答案1

得分: -1

在你的示例中,你正在使用 Scanner 从输入流中读取数据,但它非常慢,应改为使用 BufferedReader
示例

try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
     String line = reader.readLine();
     ....
} catch (IOException e) {
     e.printStackTrace();
}

这将加快你的执行时间。

英文:

In your example, you are using Scanner to read data from the input stream but its extremely slow, use BufferedReader instead.
Example:

try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
     String line = reader.readLine();
     ....
} catch (IOException e) {
     e.printStackTrace();
}

That will speed up your execution time.

huangapple
  • 本文由 发表于 2020年4月10日 15:26:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/61135742.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定