Java面试宝典——寻找数组最值 + 寻找数组中第二大的数

4 篇文章 0 订阅

求数组的最大值与最小值

package demos.array;
/** 
 * @author wyl
 * @time 2018年7月9日下午2:44:35
 * 寻找数组中的最大值与最小值
 */
public class MaxAndMin {

	static int Max;
	static int Min;
	public static void getMaxAndMin(int[] arr){
		Max=arr[0];
		Min=arr[0];
		for(int i=1;i<arr.length;i++){
			Max=arr[i]>Max?arr[i]:Max;
			Min=arr[i]<Min?arr[i]:Min;
		}
		System.out.println("MAX:"+Max);
		System.out.println("MIn:"+Min);
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] arr={4,6,89,45,2,10};
		getMaxAndMin(arr);
	}

}

找出数组中第二大的数

通过一次扫描即可得到数组中第二大的数,即通过设置两个变量来进行判断。

先定义两个变量:

    一个变量用来存储数组的最大值,初始值为数组首元素;

    另一个变量用来存储数组元素第二大数,初始值为最小负整数 Integer.Min_VALUE;

    然后遍历数组。

    如果数组元素的值比最大数变量的值大,

            则将第二大数的值更新为最大数变量的值,最大数变量的值更新为该数组元素的值;

    若数组元素的值比最大数的值小,则判断该数组元素的值是否比第二大数的值大;

    若数组元素的值比最大数的值大,则更新第二大数的值为该数组元素的值。


package demos.array;
/** 
 * @author wyl
 * @time 2018年7月9日下午2:44:35
 * 寻找数组中的最大值与最小值
 */
public class SecondMax {

	static int Max;
	static int sec_max;
	public static int getSecondMax(int[] arr){
		Max=arr[0];
		sec_max=Integer.MIN_VALUE;//第二大的值是最小负整数
		for(int i=1;i<arr.length;i++){
			if (arr[i]>Max) {
				sec_max=Max;
				Max=arr[i];
			}else {
				sec_max=arr[i]>sec_max?arr[i]:sec_max;
			}
		}
		return sec_max;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] arr={4,6,89,45,2,10};
		System.out.println(getSecondMax(arr));
	}

}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Baymax_wyl

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

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

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

打赏作者

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

抵扣说明:

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

余额充值