[来自hackerearth的Play-with-numbers-2问题。。。。我发现时间限制超过问题]https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/play-with-numbers-2/]
import java.util.Scanner;
public class PlayWithNumbers {
public static void main(String[] args) {
Scanner obj=new Scanner(System.in);
long n=obj.nextLong();
long qry=obj.nextLong();
long arr[]=new long[(int) n];
for (int i = 0; i <n ; i++) {
arr[i]=obj.nextInt();
}
for (int j = 0; j <qry ; j++) {
long sum=0;
double ans=0;
int L=obj.nextInt();
int R=obj.nextInt();
sum=(L+R)/2;
ans=Math.floor(sum);
System.out.println((int) ans);
}
}
}
第一:你的解决方案是错误的。 问题很明显是说明L和R是子数组的索引(而不是值),并且使用作为值来求平均值。
第二:扫描仪类是非常容易的,需要较少的打字,但不推荐,因为它是非常慢的。 相反,使用BufferReader。
下面是我的解决方案:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PlayWithNumbers {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
long n=Integer.parseInt(st.nextToken());
long qry=Integer.parseInt(st.nextToken());
long arr[]=new long[(int) n];
st = new StringTokenizer(br.readLine());
// read every number, adding with previous all numbers and store in the array index
arr[0] = Integer.parseInt(st.nextToken());
for (int i = 1; i <n ; i++) {
arr[i]=arr[i-1]+Integer.parseInt(st.nextToken());
}
for (int j = 0; j <qry ; j++) {
long sum=0;
double ans=0;
st = new StringTokenizer(br.readLine());
int L=Integer.parseInt(st.nextToken());
int R=Integer.parseInt(st.nextToken());
// check if the value 1 then don't subtract left value (as in that case there won't be any left value
// otherwise subtract just left most value from the array
if (L == 1) {
sum=arr[R-1]/(R-L+1);
} else {
sum=(arr[R-1] - arr[L-2])/(R-L+1);
}
ans=Math.floor(sum);
System.out.println((int) ans);
}
}
}
如果你需要澄清,请告诉我。