在竞争性编程中,我使用Integer而不是int,但它使我出现TLE错误您能告诉我为什么吗?基本上我只需要对数组进行排序并遍历它。我的代码在这里
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++;
}
}
}
在您的示例中,您正在使用Scanner
从输入流中读取数据,但是它非常慢,请改用BufferedReader
。示例:
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
String line = reader.readLine();
....
} catch (IOException e) {
e.printStackTrace();
}
这将缩短您的执行时间。