企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 1. 求数组中最大值 在前面两道题中,我们知道都使用了分治的思想。且找到了子问题,也就是左边和右边的比较,或者是两个子数组的排序。那么类似的,在使用递归的求数组中的最大值的时候,我们也需要首先找到子问题。由于是找最值问题,故而我们最终的子问题为比较问题。那么如果我们可以将数组拆分为两半,然后找到各自的最大值,最终返回这两个值中最大的那个即为最终答案。 也就是此时的问题变为: ~~~ /** * 递归的查找数组中的最大值 * @param arr 待查找数组 * @return 最大值 */ public int getMaximumByRecursion(int[] arr){ if(arr == null || arr.length == 0) return -1; return getMaximumValue(arr, 0, arr.length - 1); } private int getMaximumValue(int[] arr, int left, int right) { if(left == right) return arr[left]; int mid = left + ((right - left) >> 1); int leftMaxValue = getMaximumValue(arr, left, mid); int rightMaxValue = getMaximumValue(arr, mid + 1, right); return Math.max(leftMaxValue, rightMaxValue); } ~~~