英文:
Play With Numbers Programming Challenge (finding mean value of subarray in java)
问题
import java.io.*;
import java.util.*;
class TestClass
{
public static void main(String args[]) throws IOException
{
Scanner sc=new Scanner(System.in);
int n= sc.nextInt();
int q= sc.nextInt();
int arr[]=new int[n];
int sums[]=new int[n+1];
sums[0]=0;
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
sums[i+1]=sums[i]+arr[i];
}
for(int i=0;i<q;i++)
{
int q1=sc.nextInt();
int q2=sc.nextInt();
int end=(q2-q1)+1;
int mean= (sums[q2]-sums[q1-1])/end;
System.out.println(mean);
}
}
}
英文:
I'm trying to solve this Play With Numbers. I have passed the test cases but, I kept getting time limit exceeded. Can someone help me improve its performance in order to pass the time limit, please?
Problem:
You are given an array of n numbers and q queries. For each query you have to print the floor of the expected value(mean) of the subarray from L to R.
Input:
First line contains two integers N and Q denoting number of array elements and number of queries.
Next line contains N space seperated integers denoting array elements.
Next Q lines contain two integers L and R(indices of the array).
Output:
print a single integer denoting the answer.
Constraints:
1<= N ,Q,L,R <= 10^6
1<= Array elements <= 10^9
My code:
import java.io.*;
import java.util.*;
class TestClass
{
public static void main(String args[] ) throws IOException
{
Scanner sc=new Scanner(System.in);
int n= sc.nextInt();
int q= sc.nextInt();
int arr[]=new int[n];
int sums[]=new int[n+1];
sums[0]=0;
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
sums[i+1]=sums[i]+arr[i];
}
for(int i=0;i<q;i++)
{
int q1=sc.nextInt();
int q2=sc.nextInt();
int end=(q2-q1)+1;
int mean= (sums[q2]-sums[q1-1])/end;
System.out.println(mean);
}
}
}
答案1
得分: 0
根据我的非科学测试,这将加快速度:
sc.nextLine(); // 完成第一行
String line = sc.nextLine();
String[] parts = line.split(" ");
for (int i = 0; i < parts.length; i++) {
arr[i] = Integer.parseInt(parts[i]);
sums[i + 1] = sums[i] + arr[i];
}
正如您所见,小技巧是尽量减少 Scanner 需要进行的读取次数(因为每次“读取”通常都会有一些“延迟”)。我从文件中读取,而不是从 System.in 中读取,所以在您的设置中可能看不到同样的改进。
英文:
According to my not-so-scientific tests, this doubles the speed:
sc.nextLine(); // to finish row #1
String line = sc.nextLine();
String[] parts = line.split(" ");
for (int i = 0; i < parts.length; i++) {
arr[i] = Integer.parseInt(parts[i]);
sums[i + 1] = sums[i] + arr[i];
}
As you see, the little trick is to minimize the number of reads that the Scanner has to to (as there normally is a bit of 'lag' surrounding each 'read'). I read from a file, not from System.in, so maybe you will not see the same improvement in your setup.
专注分享java语言的经验与见解,让所有开发者获益!
评论