我们得到的数组大小为<2000
和A [i] <10 ^ 6。我知道蛮力法。我们能在线性时间内做得更好吗?
我正在检查每个子数组,并将其平均值与其他元素进行比较。
答案 0 :(得分:0)
public class FindingSubArray {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
ArrayList<Integer> a = new ArrayList<>();
ArrayList<Integer> b = new ArrayList<>();
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
double avg1 = getAverage(i,j,arr);
double avg2 = getAverageOfRest(i,j,arr);
//System.out.println(avg1+" "+avg2);
if(avg1 > avg2) {
a.add(i+1);
b.add(j+1);
}
}
}
System.out.println(a.size());
for(int i=0;i<a.size();i++){
System.out.println(a.get(i)+" "+b.get(i));
}
}
private static double getAverageOfRest(int i, int j, int[] arr) {
double result = 0;
int count = 0;
for(int k=0;k<i;k++) {
result += arr[k] ;
count ++;
}
for(int k=j+1;k<arr.length;k++) {
result += arr[k] ;
count ++;
}
if(count > 0)
return result/count;
else
return 0;
}
private static double getAverage(int i, int j, int[] arr) {
double result = 0;
int count = 0;
for (int k = i; k <= j; k++) {
result += arr[k] ;
count ++;
}
if(count > 0)
return result/count;
else
return 0;
}
}