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

求数组的最大值与最小值

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));
	}

}

猜你喜欢

转载自blog.csdn.net/u014067137/article/details/80970145