递归查找数组中的最大值
来源:互联网 发布:noesis.javascript 编辑:程序博客网 时间:2024/06/02 07:12
递归查找数组中的最大值
2017-10-13 晚上趋势科技的笔试题
题目
查找数组中的最大值,使用递归
思路
递归操作:
将数组分为两个部分,第一个元素是第一部分,剩余元素是第二部分,返回这两个部分的较大者;
递归终止条件:
当第二部分的长度等于1,也即是第二部分的仅有最后一个元素时,返回该元素
程序
package base;import org.junit.Test;import java.util.Arrays;/** * description: * * @author liyazhou * @since 2017-10-15 17:21 */public class Date20171015_Recursive { public int max(int[] arr, int i){ if (i == arr.length-1) return arr[i]; return Math.max(arr[i], max(arr, i+1)); } @Test public void test(){ int[][] arrs = { {1, 5, 6, 3, 2}, {1, 0}, {6, -1, 4}, {1}, }; for (int[] arr : arrs) System.out.println(Arrays.toString(arr) + " :: " + max(arr, 0)); }}
测试结果
[1, 5, 6, 3, 2] :: 6[1, 0] :: 1[6, -1, 4] :: 6[1] :: 1
另一版本
2017-10-16 19:51:50
int max = Integer.MIN_VALUE; public void getMax(int[] arr, int i){ if (i < arr.length) max = Math.max(max, arr[i]); else return; getMax(arr, i+1); } public int getMax(int[] arr){ if (arr == null || arr.length == 0) throw new RuntimeException("参数异常"); getMax(arr, 0); return max; }
阅读全文
1 0
- 递归查找数组中的最大值
- 查找数组中的最大值
- 数组中的最大值 -- 递归二分
- 递归求解数组中的最大值
- 递归求解数组中的最大值
- 【java】递归求数组中的最大值
- C++查找数组中的最大值和最小值
- 求数组中的最大值 —用递归算法求数组中的最大值。
- 寻找数组中的最大值和最小值(递归…
- Java利用递归的方法求整数数组中的最大值
- 高性能查找数组中的最大值和最小值
- java递归求数组最大值
- Java 递归求数组最大值
- 递归方法求数组最大值
- 升序降序数组查找最大值
- 返回数组中的最大值
- 求数组中的最大值
- 找出数组中的最大值
- @SelectProvider,@Select和xml用法的一点理解
- java使用poi读取存储excel表格,包括xls和xlsx格式
- 2.4ArrayList和LinkedList的区别及详细原因
- imageLoader代码使用
- 分饼干
- 递归查找数组中的最大值
- angularjs之购物
- div垂直居中
- 排错神器error_reporting 和display_errors
- 安卓中常用的权限和依赖
- 欢迎使用CSDN-markdown编辑器
- php Thinkphp结合composer实现smtp发送邮件
- 155. Min Stack(栈)
- DP 长寿花