英文:
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<=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++;
}
}
}
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论