Java查找数组最大值的一些方法

1.循环比对
2.递归
3.依赖Arrays.sort()
4.利用Arrays.stream()

1.循环比对

public class ArrayMaxTest {
    public static void main(String[] args) {
        int[] arr = {3, 7, 2, 1, -4};
        int max = findMaxByFor(arr); // 查找最大值
        System.out.println("最大值是:" + max);
    }

    /**
     * 通过 for 循环查找最大值
     * @param arr 待查询数组
     * @return 最大值
     */
    private static int findMaxByFor(int[] arr) {
        int max = 0; // 最大值
        for (int item : arr) {
            if (item > max) { // 当前值大于最大值,赋值为最大值
                max = item;
            }
        }
        return max;
    }
}

2.递归

public class ArrayMax {
    public static void main(String[] args) {
        int[] arr = {3, 7, 2, 1, -4};
        int max = findMaxByRecursive(arr, 0, arr.length - 1, 0); // 根据 Collections 查找最大值
        System.out.println("最大值是:" + max);
    }

    /**
     * 根据递归查询最大的值
     * @param arr  待查询数组
     * @param head 最前面的元素的下标
     * @param last 最末尾的元素的下标
     * @param max  (临时)最大值
     * @return 最大值
     */
    private static int findMaxByRecursive(int[] arr, int head, int last, int max) {
        if (head == last) {
            // 递归完了,返回结果
            return max;
        } else {
            if (arr[head] > arr[last]) {
                max = arr[head]; // 赋最大值
                // 从后往前移动递归
                return findMaxByRecursive(arr, head, last - 1, max);
            } else {
                max = arr[last]; // 赋最大值
                // 从前往后移动递归
                return findMaxByRecursive(arr, head + 1, last, max);
            }
        }
    }
}

3.Arrays.sort()

import java.util.Arrays;

public class ArrayMax {
    public static void main(String[] args) {
        int[] arr = {3, 7, 2, 1, -4};
        int max = findMaxBySort(arr); // 根据 Arrays.sort 查找最大值
        System.out.println("最大值是:" + max);
    }

    /**
     * 根据 Arrays.sort 查找最大值
     * @param arr 待查询数组
     * @return 最大值
     */
    private static int findMaxBySort(int[] arr) {
        Arrays.sort(arr);
        return arr[arr.length - 1];
    }
}

4.利用Arrays.stream()

import java.util.Arrays;

public class ArrayMax {
    public static void main(String[] args) {
        int[] arr = {3, 7, 2, 1, -4};
        int max = findMaxByStream(arr); // 根据 stream 查找最大值
        System.out.println("最大值是:" + max);
    }

    /**
     * 根据 stream 查找最大值
     * @param arr 待查询数组
     * @return 最大值
     */
    private static int findMaxByStream(int[] arr) {
        return Arrays.stream(arr).max().getAsInt();
    }
}
  • 5
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值