递归查找数组中的最大值
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;
}