import java.util.Arrays;
import java.util.Scanner;
public class EqualMedian {
static int median(int[] a, int[] b, int mid, int[] temp) {
int count = 0;
if (a[mid] != b[mid]) {
temp[0] = a[mid];
a[mid] = b[mid];
b[mid] = temp[0];
Arrays.sort(a);
Arrays.sort(b);
count++;
median(a, b, mid, temp);
}
return count;
}
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int j = 0; j < t; j++) {
int n = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
b[i] = sc.nextInt();
}
int[] temp = { 0 };
int mid = (n / 2) + 1;
int ans = median(a, b, mid, temp);
System.out.println(ans);
}
}
}
OUTPUT: Execution failed. Stack Trace: Exception in thread "main" java.lang.StackOverflowError at java.util.DualPivotQuicksort.sort(DualPivotQuicksort.java:111) at java.util.Arrays.sort(Arrays.java:144) at Equal_median.median(Equal_median.java:16) at Equal_median.median(Equal_median.java:19) Equal_median.median(Equal_median.java:19) at Equal_median.median(Equal_median.java:19)
您只是交换 a[mid] 和 b[mid] 并且它们永远不会相等,它将以无限递归调用结束,因此会出现 stackocverflow 错误。
So your final goal is to determine if 2 arrays have equal median, and if so, print the median? You should make a method that computes the median for only one array. Call this method for each array in main. No need for recursion.
public static int median(int []myArray) {
int mid = (myArray.length() / 2) + 1;
return myArray[mid]
}
public static void main(String args[]) {
...
int firstMedian = median(a);
int secondMedian = median(b);
if(firstMedian == secondMedian) {
System.out.println(firstMedian);
}
}
Recursion should not be used without setting proper ending conditions. So.. always double-check your condition. Most recursions have a for/while loop equivalent. If the condition in a while loop sounds like it will go to infinity, it's probably a bad idea.
Also, if a variable can be computed locally and serves no purpose after the method (such as temp
), don't make it a parameter! Just declare it locally.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.