java - 递归查找并返回数组中的最小值和最大值
问题描述
该函数仅获取 2 个参数:数字的 arr 和 n 表示它们在数组中的数量。我需要递归查找并返回数组中的最小值和最大值。以3n/2比较 的最小复杂度。下面的代码仅返回 MIN。我应该如何使它返回 MIN 和 MAX?
public class MyClass {
public static void main(String[] args) {
int A[] = { 1, 4, 45, 6, -50, 10, 2 };
int n = A.length;
// Function calling
System.out.println(findMinMaxRec(A, n));
}
public static int findMinMaxRec(int A[], int n) {
// if size = 0 means whole array
// has been traversed
if (n == 1)
return A[0];
for (int i = 0; i < n; i++)
return Math.min(A[n - 1], findMinMaxRec(A, n - 1));
// The program NO return min and max (both)
return Math.max(A[n - 1], findMinMaxRec(A, n - 1));
}
}
答案:
-50
45
解决方案
两个版本,一个按升序排列,一个按降序排列:
static int[] findMinMaxRecDesc(int[] A, int n) {
if (n == 0) {
return new int[]{A[0], A[0]};
}
int[] recResult = findMinMaxRecDesc(A, n - 1);
return new int[]{Math.min(A[n - 1], recResult[0]), Math.max(A[n - 1], recResult[1])};
}
static int[] findMinMaxRecAsc(int[] A, int n) {
if (n == A.length - 1) {
return new int[]{A[n], A[n]};
}
int[] recResult = findMinMaxRecAsc(A, n + 1);
return new int[]{Math.min(A[n], recResult[0]), Math.max(A[n], recResult[1])};
}
public static void main(String[] args) {
int[] array = {1, 4, 45, 6, -50, 10, 2};
int[] result = Arrays.toString(findMinMaxRecAsc(array, array.length))
System.out.println(result); // [-50, 45]
}
并且该方法findMinMaxRec
被称为n+1
times,所以它是线性的,就像一个for循环
推荐阅读
- javascript - 警告:React.createElement:在组件中使用组件时类型无效
- permissions - 可以在 Facebook 登录 oauth 中删除访问用户个人资料图片的权限吗?
- youtube-api - 我正在尝试停止通过 youtube 数据 api 获得的 youtube 视频上的广告
- javascript - 使用 Blazor 多次调用 JS 互操作
- c++ - ncurses getyx(win, y, x) 总是返回 '0,0'。为什么?
- python - 如何在 python MySQLDB VALUE 子句中插入字符串列表
- linux - 如何在 Gentoo 中列出已安装的屏蔽包?
- php - 自动登录 WKwebview
- mysql - 实际解决方案与我的解决方案有什么区别?
- javascript - Electron构建访问静态图片vue js