public static int[] max_min(int[] a){ //res[0] records the minimum value while res[1] records the maximal one. int res[] = new int[2]; int n = a.length; if(n == 0) { return res; } if(n == 1) { res[0] = res[1] = a[0]; } int min, max; if(n%2 == 1) { res[0] = res[1] = a[0]; for(int i=1; i<=n-2; i+=2) { if(a[i] < a[i+1]) { min = a[i]; max = a[i+1]; } else { min = a[i+1]; max = a[i]; } res[0] = Math.min(min, res[0]); res[1] = Math.max(max, res[1]); } } else { res[0] = Math.min(a[0], a[1]); res[1] = Math.max(a[0], a[1]); for(int i=2; i<=n-2; i+=2) { if(a[i] < a[i+1]) { min = a[i]; max = a[i+1]; } else { min = a[i+1]; max = a[i]; } res[0] = Math.min(min, res[0]); res[1] = Math.max(max, res[1]); } } return res; }
时间: 2024-10-24 18:02:09