Java中取得数组中最大(小)元素的几种实现方法

本文探讨了在Java中找到数组最大值的三种方法:迭代、递归和使用Java8的Stream API。通过自定义比较函数,可以实现更灵活的比较操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简介

本篇文章将主要介绍获取数组中最大(小)元素的基本方法,以及其在Java中的几种实现方法。

算法

取得数组中最大(小)元素的基本算法一般都类似于如下所示:

SET MAX to array[0]
FOR i  = 1 to array.length - 1
    IF array[i] > MAX THEN
        SET MAX to array[i]
    ENDIF
ENDFOR

对于java而言,这一算法逻辑可以有多种不同的实现方式。但无论如何实现,因为在算法中我们需要检查数组中的每一个元素,所以其时间复杂度都是O(n),这里n指的是数组的长度。

迭代(iteration)实现

public int getMaxWithIteration(int[] nums) {
	if (nums == null || nums.length == 0) {
		throw new IllegalArgumentException("Input array should not be empty!");
	}
	int max = Integer.MIN_VALUE;
	for (int i = 0; i < nums.length; i++) {
		if (nums[i] > max) {
			max = nums[i];
		}
	}

	return max;
}

递归(recursion)实现

public int getMaxWithRecursion(int[] nums) {
	if (nums == null || nums.length == 0) {
		throw new IllegalArgumentException("Input array should not be empty!");
	}
	return getMax(nums, 0, Integer.MIN_VALUE);
}

private int getMax(int[] nums, int currIdx, int currMax) {
	if (currIdx >= nums.length) return currMax;

	return getMax(nums, currIdx + 1, Math.max(nums[currIdx], currMax));
}

利用Java8的stream方法

public int getMaxWithStream(int[] nums) {
	if (nums == null || nums.length == 0) {
		throw new IllegalArgumentException("Input array should not be empty!");
	}

	return Arrays.stream(integers).max().getAsInt();
}

我们甚至可以给这里的max()函数传入一个自定义的比较函数来实现自定义的比较功能,非常方便,如下面的例子所示。

public class Product {
	private String name;
	private int price;

	public Product(String name, int price) {
		this.name = name;
		this.price = price;
	}

	public int getPrice() {
		return this.price;
	}

	public String getName() {
		return this.name;
	}

	public static Product getMostExpensiveProduct(Product[] products) {
		return Arrays.stream(products)
		.max(Comparator.comparing(Product::getPrice))
		.orElseThrow(NoSuchElementException::new); 
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

耀凯考前突击大师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值