算法基础之寻找第二大的数

仅适用于规模N较小的情况。
大致思路:遍历一遍,不断更新max和secondMax。
需要注意两点:1.元素个数小于两个(这个有点打酱油。。)  2.所有元素值相同
代码如下:
import java.util.Arrays;

/**
 * 寻找第二大的数:规模N较小的情况
 * 
 * @author aaron-han
 * 
 */
public class FindSecondMax {

	public static void main(String[] args) {
		int[] arr = com.utils.Utils.randomIntArray();
		System.out.println(Arrays.toString(arr));
		findSecondMax(arr);
	}

	public static void findSecondMax(int[] arr) {
		int length = arr.length;
		if (length < 2) {
			System.out.println("Usage: at least two numbers in array.");
			System.exit(-1);
		}
		int max = arr[0];
		int secondMax = Integer.MIN_VALUE;
		for (int i = 1; i < arr.length; i++) {
			if (arr[i] > max) {
				secondMax = max;
				max = arr[i];
			} else if (arr[i] > secondMax && arr[i] < max) {
				secondMax = arr[i];
			}
		}
		if (secondMax == Integer.MIN_VALUE) {
			System.out.println("No secondMax Number.");
		} else {
			System.out.println("The secondMax = " + secondMax);
		}
	}

}


对于N较大的情况,目前的想法是直接快排,然后取index为1的。
欢迎大家指点更好的思路,后边有想法了我会写上来。

猜你喜欢

转载自aaron-han.iteye.com/blog/1468948